2020-03-05 18:07:42 -03:00
|
|
|
//! Candidate selection. See the [rustc dev guide] for more information on how this works.
|
2018-02-25 15:24:14 -06:00
|
|
|
//!
|
2020-03-09 18:33:04 -03:00
|
|
|
//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html#selection
|
2014-09-12 10:53:35 -04:00
|
|
|
|
2014-11-06 00:05:53 -08:00
|
|
|
use self::EvaluationResult::*;
|
2018-09-07 09:34:09 -04:00
|
|
|
use self::SelectionCandidate::*;
|
2014-11-06 00:05:53 -08:00
|
|
|
|
2017-11-22 23:01:51 +02:00
|
|
|
use super::coherence::{self, Conflict};
|
2020-08-06 10:00:08 +02:00
|
|
|
use super::const_evaluatable;
|
2015-02-19 10:30:45 -05:00
|
|
|
use super::project;
|
2020-05-25 22:33:21 +02:00
|
|
|
use super::project::normalize_with_depth_to;
|
2020-07-24 19:10:22 +01:00
|
|
|
use super::project::ProjectionTyObligation;
|
2018-09-07 09:34:09 -04:00
|
|
|
use super::util;
|
2020-01-05 20:27:00 +01:00
|
|
|
use super::util::{closure_trait_ref_and_return_type, predicate_for_trait_def};
|
2020-01-05 20:52:34 +01:00
|
|
|
use super::wf;
|
2018-09-07 09:34:09 -04:00
|
|
|
use super::DerivedObligationCause;
|
2021-09-14 15:38:53 -05:00
|
|
|
use super::Normalized;
|
2020-05-25 22:33:21 +02:00
|
|
|
use super::Obligation;
|
|
|
|
use super::ObligationCauseCode;
|
2015-03-28 02:23:20 -07:00
|
|
|
use super::Selection;
|
|
|
|
use super::SelectionResult;
|
2020-02-08 19:14:50 +01:00
|
|
|
use super::TraitQueryMode;
|
2021-10-22 10:56:32 -03:00
|
|
|
use super::{ErrorReporting, Overflow, SelectionError};
|
2018-09-07 09:34:09 -04:00
|
|
|
use super::{ObligationCause, PredicateObligation, TraitObligation};
|
|
|
|
|
2020-05-22 17:48:07 +00:00
|
|
|
use crate::infer::{InferCtxt, InferOk, TypeFreshener};
|
2020-02-22 11:44:18 +01:00
|
|
|
use crate::traits::error_reporting::InferCtxtExt;
|
2021-10-09 11:29:39 -05:00
|
|
|
use crate::traits::project::ProjectionCacheKeyExt;
|
|
|
|
use crate::traits::ProjectionCacheKey;
|
2019-12-24 05:02:53 +01:00
|
|
|
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
|
2020-03-14 20:13:55 +02:00
|
|
|
use rustc_data_structures::stack::ensure_sufficient_stack;
|
2022-01-22 18:49:12 -06:00
|
|
|
use rustc_errors::Diagnostic;
|
2020-01-05 02:37:57 +01:00
|
|
|
use rustc_hir as hir;
|
2020-01-30 02:42:33 +01:00
|
|
|
use rustc_hir::def_id::DefId;
|
2021-02-12 22:07:46 +00:00
|
|
|
use rustc_infer::infer::LateBoundRegionConversionTime;
|
2020-03-29 17:19:48 +02:00
|
|
|
use rustc_middle::dep_graph::{DepKind, DepNodeIndex};
|
2020-02-29 10:03:04 +13:00
|
|
|
use rustc_middle::mir::interpret::ErrorHandled;
|
2021-09-07 01:56:29 +01:00
|
|
|
use rustc_middle::thir::abstract_const::NotConstEvaluatable;
|
2022-02-21 13:44:55 +01:00
|
|
|
use rustc_middle::ty::fast_reject::{self, TreatParams};
|
2020-09-02 10:40:56 +03:00
|
|
|
use rustc_middle::ty::print::with_no_trimmed_paths;
|
2020-03-29 17:19:48 +02:00
|
|
|
use rustc_middle::ty::relate::TypeRelation;
|
2020-05-25 22:33:21 +02:00
|
|
|
use rustc_middle::ty::subst::{GenericArgKind, Subst, SubstsRef};
|
2020-07-24 19:10:22 +01:00
|
|
|
use rustc_middle::ty::{self, PolyProjectionPredicate, ToPolyTraitRef, ToPredicate};
|
2021-07-22 21:56:07 +08:00
|
|
|
use rustc_middle::ty::{Ty, TyCtxt, TypeFoldable};
|
2020-01-01 19:30:57 +01:00
|
|
|
use rustc_span::symbol::sym;
|
2020-01-30 02:42:33 +01:00
|
|
|
|
2019-06-11 19:05:08 -04:00
|
|
|
use std::cell::{Cell, RefCell};
|
2017-06-30 14:18:04 +03:00
|
|
|
use std::cmp;
|
2018-12-20 04:02:12 -05:00
|
|
|
use std::fmt::{self, Display};
|
2018-09-07 09:34:09 -04:00
|
|
|
use std::iter;
|
2014-09-12 10:53:35 -04:00
|
|
|
|
2020-03-29 16:41:09 +02:00
|
|
|
pub use rustc_middle::traits::select::*;
|
2020-01-22 09:01:22 +01:00
|
|
|
|
2020-05-25 22:08:30 +02:00
|
|
|
mod candidate_assembly;
|
2020-05-25 22:33:21 +02:00
|
|
|
mod confirmation;
|
2020-05-25 22:08:30 +02:00
|
|
|
|
2020-08-02 15:09:07 +02:00
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
pub enum IntercrateAmbiguityCause {
|
|
|
|
DownstreamCrate { trait_desc: String, self_desc: Option<String> },
|
|
|
|
UpstreamCrateUpdate { trait_desc: String, self_desc: Option<String> },
|
|
|
|
ReservationImpl { message: String },
|
|
|
|
}
|
|
|
|
|
|
|
|
impl IntercrateAmbiguityCause {
|
|
|
|
/// Emits notes when the overlap is caused by complex intercrate ambiguities.
|
|
|
|
/// See #23980 for details.
|
2022-01-23 20:41:46 +00:00
|
|
|
pub fn add_intercrate_ambiguity_hint(&self, err: &mut Diagnostic) {
|
2020-08-02 15:09:07 +02:00
|
|
|
err.note(&self.intercrate_ambiguity_hint());
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn intercrate_ambiguity_hint(&self) -> String {
|
|
|
|
match self {
|
2021-01-02 20:09:17 +01:00
|
|
|
IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc } => {
|
|
|
|
let self_desc = if let Some(ty) = self_desc {
|
2020-08-02 15:09:07 +02:00
|
|
|
format!(" for type `{}`", ty)
|
|
|
|
} else {
|
|
|
|
String::new()
|
|
|
|
};
|
|
|
|
format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
|
|
|
|
}
|
2021-01-02 20:09:17 +01:00
|
|
|
IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_desc, self_desc } => {
|
|
|
|
let self_desc = if let Some(ty) = self_desc {
|
2020-08-02 15:09:07 +02:00
|
|
|
format!(" for type `{}`", ty)
|
|
|
|
} else {
|
|
|
|
String::new()
|
|
|
|
};
|
|
|
|
format!(
|
|
|
|
"upstream crates may add a new impl of trait `{}`{} \
|
|
|
|
in future versions",
|
|
|
|
trait_desc, self_desc
|
|
|
|
)
|
|
|
|
}
|
2021-01-02 20:09:17 +01:00
|
|
|
IntercrateAmbiguityCause::ReservationImpl { message } => message.clone(),
|
2020-08-02 15:09:07 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-14 19:39:39 +03:00
|
|
|
pub struct SelectionContext<'cx, 'tcx> {
|
2019-06-14 00:48:52 +03:00
|
|
|
infcx: &'cx InferCtxt<'cx, 'tcx>,
|
2015-06-25 13:08:10 -07:00
|
|
|
|
2018-09-07 09:46:53 -04:00
|
|
|
/// Freshener used specifically for entries on the obligation
|
|
|
|
/// stack. This ensures that all entries on the stack at one time
|
|
|
|
/// will have the same set of placeholder entries, which is
|
|
|
|
/// important for checking for trait bounds that recursively
|
|
|
|
/// require themselves.
|
2019-06-14 00:48:52 +03:00
|
|
|
freshener: TypeFreshener<'cx, 'tcx>,
|
2014-11-03 14:48:03 -05:00
|
|
|
|
2018-11-27 02:59:49 +00:00
|
|
|
/// If `true`, indicates that the evaluation should be conservative
|
2014-11-03 14:48:03 -05:00
|
|
|
/// and consider the possibility of types outside this crate.
|
|
|
|
/// This comes up primarily when resolving ambiguity. Imagine
|
2018-11-27 02:59:49 +00:00
|
|
|
/// there is some trait reference `$0: Bar` where `$0` is an
|
2014-11-03 14:48:03 -05:00
|
|
|
/// inference variable. If `intercrate` is true, then we can never
|
|
|
|
/// say for sure that this reference is not implemented, even if
|
|
|
|
/// there are *no impls at all for `Bar`*, because `$0` could be
|
|
|
|
/// bound to some type that in a downstream crate that implements
|
|
|
|
/// `Bar`. This is the suitable mode for coherence. Elsewhere,
|
|
|
|
/// though, we set this to false, because we are only interested
|
|
|
|
/// in types that the user could actually have written --- in
|
2018-11-27 02:59:49 +00:00
|
|
|
/// other words, we consider `$0: Bar` to be unimplemented if
|
2014-11-03 14:48:03 -05:00
|
|
|
/// there is no type that the user could *actually name* that
|
|
|
|
/// would satisfy it. This avoids crippling inference, basically.
|
2020-02-08 19:14:50 +01:00
|
|
|
intercrate: bool,
|
2016-05-11 14:40:24 -07:00
|
|
|
|
2018-01-26 17:21:43 -05:00
|
|
|
intercrate_ambiguity_causes: Option<Vec<IntercrateAmbiguityCause>>,
|
Generate documentation for auto-trait impls
A new section is added to both both struct and trait doc pages.
On struct/enum pages, a new 'Auto Trait Implementations' section displays any
synthetic implementations for auto traits. Currently, this is only done
for Send and Sync.
On trait pages, a new 'Auto Implementors' section displays all types
which automatically implement the trait. Effectively, this is a list of
all public types in the standard library.
Synthesized impls for a particular auto trait ('synthetic impls') take
into account generic bounds. For example, a type 'struct Foo<T>(T)' will
have 'impl<T> Send for Foo<T> where T: Send' generated for it.
Manual implementations of auto traits are also taken into account. If we have
the following types:
'struct Foo<T>(T)'
'struct Wrapper<T>(Foo<T>)'
'unsafe impl<T> Send for Wrapper<T>' // pretend that Wrapper<T> makes
this sound somehow
Then Wrapper will have the following impl generated:
'impl<T> Send for Wrapper<T>'
reflecting the fact that 'T: Send' need not hold for 'Wrapper<T>: Send'
to hold
Lifetimes, HRTBS, and projections (e.g. '<T as Iterator>::Item') are
taken into account by synthetic impls
However, if a type can *never* implement a particular auto trait
(e.g. 'struct MyStruct<T>(*const T)'), then a negative impl will be
generated (in this case, 'impl<T> !Send for MyStruct<T>')
All of this means that a user should be able to copy-paste a synthetic
impl into their code, without any observable changes in behavior
(assuming the rest of the program remains unchanged).
2017-11-22 16:16:55 -05:00
|
|
|
|
|
|
|
/// Controls whether or not to filter out negative impls when selecting.
|
|
|
|
/// This is used in librustdoc to distinguish between the lack of an impl
|
|
|
|
/// and a negative impl
|
2018-04-19 02:28:03 -05:00
|
|
|
allow_negative_impls: bool,
|
|
|
|
|
|
|
|
/// The mode that trait queries run in, which informs our error handling
|
|
|
|
/// policy. In essence, canonicalized queries need their errors propagated
|
|
|
|
/// rather than immediately reported because we do not have accurate spans.
|
|
|
|
query_mode: TraitQueryMode,
|
2017-07-23 22:30:47 +09:00
|
|
|
}
|
|
|
|
|
2014-09-18 11:08:04 -04:00
|
|
|
// A stack that walks back up the stack frame.
|
2019-06-14 19:39:39 +03:00
|
|
|
struct TraitObligationStack<'prev, 'tcx> {
|
2014-12-05 00:03:03 -05:00
|
|
|
obligation: &'prev TraitObligation<'tcx>,
|
2014-09-12 10:53:35 -04:00
|
|
|
|
2021-12-12 12:34:46 +08:00
|
|
|
/// The trait predicate from `obligation` but "freshened" with the
|
2014-12-12 06:13:42 -05:00
|
|
|
/// selection-context's freshener. Used to check for recursion.
|
2021-12-12 12:34:46 +08:00
|
|
|
fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
|
2014-09-12 10:53:35 -04:00
|
|
|
|
2019-06-10 11:46:53 -04:00
|
|
|
/// Starts out equal to `depth` -- if, during evaluation, we
|
|
|
|
/// encounter a cycle, then we will set this flag to the minimum
|
|
|
|
/// depth of that cycle for all participants in the cycle. These
|
|
|
|
/// participants will then forego caching their results. This is
|
|
|
|
/// not the most efficient solution, but it addresses #60010. The
|
|
|
|
/// problem we are trying to prevent:
|
2019-05-01 13:10:01 -04:00
|
|
|
///
|
|
|
|
/// - If you have `A: AutoTrait` requires `B: AutoTrait` and `C: NonAutoTrait`
|
|
|
|
/// - `B: AutoTrait` requires `A: AutoTrait` (coinductive cycle, ok)
|
|
|
|
/// - `C: NonAutoTrait` requires `A: AutoTrait` (non-coinductive cycle, not ok)
|
|
|
|
///
|
|
|
|
/// you don't want to cache that `B: AutoTrait` or `A: AutoTrait`
|
|
|
|
/// is `EvaluatedToOk`; this is because they were only considered
|
|
|
|
/// ok on the premise that if `A: AutoTrait` held, but we indeed
|
|
|
|
/// encountered a problem (later on) with `A: AutoTrait. So we
|
|
|
|
/// currently set a flag on the stack node for `B: AutoTrait` (as
|
2019-08-01 15:13:31 +07:00
|
|
|
/// well as the second instance of `A: AutoTrait`) to suppress
|
2019-05-01 13:10:01 -04:00
|
|
|
/// caching.
|
|
|
|
///
|
2019-05-13 13:29:49 +02:00
|
|
|
/// This is a simple, targeted fix. A more-performant fix requires
|
2019-05-01 13:10:01 -04:00
|
|
|
/// deeper changes, but would permit more caching: we could
|
|
|
|
/// basically defer caching until we have fully evaluated the
|
2019-05-13 13:29:49 +02:00
|
|
|
/// tree, and then cache the entire tree at once. In any case, the
|
|
|
|
/// performance impact here shouldn't be so horrible: every time
|
|
|
|
/// this is hit, we do cache at least one trait, so we only
|
|
|
|
/// evaluate each member of a cycle up to N times, where N is the
|
|
|
|
/// length of the cycle. This means the performance impact is
|
|
|
|
/// bounded and we shouldn't have any terrible worst-cases.
|
2019-06-10 11:46:53 -04:00
|
|
|
reached_depth: Cell<usize>,
|
2019-05-01 13:10:01 -04:00
|
|
|
|
2015-03-30 17:46:34 -04:00
|
|
|
previous: TraitObligationStackList<'prev, 'tcx>,
|
2019-06-06 13:32:00 -04:00
|
|
|
|
2019-05-17 02:20:14 +01:00
|
|
|
/// The number of parent frames plus one (thus, the topmost frame has depth 1).
|
2019-06-06 13:32:00 -04:00
|
|
|
depth: usize,
|
2019-06-10 16:22:10 -04:00
|
|
|
|
2019-05-17 02:20:14 +01:00
|
|
|
/// The depth-first number of this node in the search graph -- a
|
|
|
|
/// pre-order index. Basically, a freshly incremented counter.
|
2019-06-10 16:22:10 -04:00
|
|
|
dfn: usize,
|
2014-09-17 16:12:02 -04:00
|
|
|
}
|
2014-09-12 10:53:35 -04:00
|
|
|
|
2014-12-17 14:16:28 -05:00
|
|
|
struct SelectionCandidateSet<'tcx> {
|
2019-05-17 02:20:14 +01:00
|
|
|
// A list of candidates that definitely apply to the current
|
2014-12-30 08:59:33 -05:00
|
|
|
// obligation (meaning: types unify).
|
2014-12-17 14:16:28 -05:00
|
|
|
vec: Vec<SelectionCandidate<'tcx>>,
|
2014-12-30 08:59:33 -05:00
|
|
|
|
2019-05-17 02:20:14 +01:00
|
|
|
// If `true`, then there were candidates that might or might
|
2014-12-30 08:59:33 -05:00
|
|
|
// not have applied, but we couldn't tell. This occurs when some
|
|
|
|
// of the input types are type variables, in which case there are
|
|
|
|
// various "builtin" rules that might or might not trigger.
|
|
|
|
ambiguous: bool,
|
2014-10-09 17:19:50 -04:00
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
#[derive(PartialEq, Eq, Debug, Clone)]
|
2015-12-22 10:20:47 -08:00
|
|
|
struct EvaluatedCandidate<'tcx> {
|
|
|
|
candidate: SelectionCandidate<'tcx>,
|
|
|
|
evaluation: EvaluationResult,
|
|
|
|
}
|
|
|
|
|
2016-04-14 15:49:39 +03:00
|
|
|
/// When does the builtin impl for `T: Trait` apply?
|
2021-12-19 22:01:48 -05:00
|
|
|
#[derive(Debug)]
|
2016-04-14 15:49:39 +03:00
|
|
|
enum BuiltinImplConditions<'tcx> {
|
2019-05-17 02:20:14 +01:00
|
|
|
/// The impl is conditional on `T1, T2, ...: Trait`.
|
2020-10-05 16:51:33 -04:00
|
|
|
Where(ty::Binder<'tcx, Vec<Ty<'tcx>>>),
|
2016-04-14 15:49:39 +03:00
|
|
|
/// There is no built-in impl. There may be some other
|
|
|
|
/// candidate (a where-clause or user-defined impl).
|
|
|
|
None,
|
|
|
|
/// It is unknown whether there is an impl.
|
2018-09-07 09:34:09 -04:00
|
|
|
Ambiguous,
|
2014-10-09 17:19:50 -04:00
|
|
|
}
|
|
|
|
|
2019-06-14 00:48:52 +03:00
|
|
|
impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
|
|
|
|
pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
|
2014-11-03 14:48:03 -05:00
|
|
|
SelectionContext {
|
2017-07-03 11:19:51 -07:00
|
|
|
infcx,
|
2021-07-07 10:56:26 -05:00
|
|
|
freshener: infcx.freshener_keep_static(),
|
2020-02-08 19:14:50 +01:00
|
|
|
intercrate: false,
|
2018-01-26 17:21:43 -05:00
|
|
|
intercrate_ambiguity_causes: None,
|
2018-02-10 14:34:46 -05:00
|
|
|
allow_negative_impls: false,
|
2018-04-19 02:28:03 -05:00
|
|
|
query_mode: TraitQueryMode::Standard,
|
2016-02-23 12:47:09 -08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-08 19:14:50 +01:00
|
|
|
pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> {
|
2016-02-23 12:47:09 -08:00
|
|
|
SelectionContext {
|
2017-07-03 11:19:51 -07:00
|
|
|
infcx,
|
2021-07-07 10:56:26 -05:00
|
|
|
freshener: infcx.freshener_keep_static(),
|
2020-02-08 19:14:50 +01:00
|
|
|
intercrate: true,
|
2018-01-26 17:21:43 -05:00
|
|
|
intercrate_ambiguity_causes: None,
|
2018-02-10 14:34:46 -05:00
|
|
|
allow_negative_impls: false,
|
2018-04-19 02:28:03 -05:00
|
|
|
query_mode: TraitQueryMode::Standard,
|
Generate documentation for auto-trait impls
A new section is added to both both struct and trait doc pages.
On struct/enum pages, a new 'Auto Trait Implementations' section displays any
synthetic implementations for auto traits. Currently, this is only done
for Send and Sync.
On trait pages, a new 'Auto Implementors' section displays all types
which automatically implement the trait. Effectively, this is a list of
all public types in the standard library.
Synthesized impls for a particular auto trait ('synthetic impls') take
into account generic bounds. For example, a type 'struct Foo<T>(T)' will
have 'impl<T> Send for Foo<T> where T: Send' generated for it.
Manual implementations of auto traits are also taken into account. If we have
the following types:
'struct Foo<T>(T)'
'struct Wrapper<T>(Foo<T>)'
'unsafe impl<T> Send for Wrapper<T>' // pretend that Wrapper<T> makes
this sound somehow
Then Wrapper will have the following impl generated:
'impl<T> Send for Wrapper<T>'
reflecting the fact that 'T: Send' need not hold for 'Wrapper<T>: Send'
to hold
Lifetimes, HRTBS, and projections (e.g. '<T as Iterator>::Item') are
taken into account by synthetic impls
However, if a type can *never* implement a particular auto trait
(e.g. 'struct MyStruct<T>(*const T)'), then a negative impl will be
generated (in this case, 'impl<T> !Send for MyStruct<T>')
All of this means that a user should be able to copy-paste a synthetic
impl into their code, without any observable changes in behavior
(assuming the rest of the program remains unchanged).
2017-11-22 16:16:55 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
pub fn with_negative(
|
2019-06-14 00:48:52 +03:00
|
|
|
infcx: &'cx InferCtxt<'cx, 'tcx>,
|
2018-09-07 09:34:09 -04:00
|
|
|
allow_negative_impls: bool,
|
2019-06-14 00:48:52 +03:00
|
|
|
) -> SelectionContext<'cx, 'tcx> {
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!(?allow_negative_impls, "with_negative");
|
Generate documentation for auto-trait impls
A new section is added to both both struct and trait doc pages.
On struct/enum pages, a new 'Auto Trait Implementations' section displays any
synthetic implementations for auto traits. Currently, this is only done
for Send and Sync.
On trait pages, a new 'Auto Implementors' section displays all types
which automatically implement the trait. Effectively, this is a list of
all public types in the standard library.
Synthesized impls for a particular auto trait ('synthetic impls') take
into account generic bounds. For example, a type 'struct Foo<T>(T)' will
have 'impl<T> Send for Foo<T> where T: Send' generated for it.
Manual implementations of auto traits are also taken into account. If we have
the following types:
'struct Foo<T>(T)'
'struct Wrapper<T>(Foo<T>)'
'unsafe impl<T> Send for Wrapper<T>' // pretend that Wrapper<T> makes
this sound somehow
Then Wrapper will have the following impl generated:
'impl<T> Send for Wrapper<T>'
reflecting the fact that 'T: Send' need not hold for 'Wrapper<T>: Send'
to hold
Lifetimes, HRTBS, and projections (e.g. '<T as Iterator>::Item') are
taken into account by synthetic impls
However, if a type can *never* implement a particular auto trait
(e.g. 'struct MyStruct<T>(*const T)'), then a negative impl will be
generated (in this case, 'impl<T> !Send for MyStruct<T>')
All of this means that a user should be able to copy-paste a synthetic
impl into their code, without any observable changes in behavior
(assuming the rest of the program remains unchanged).
2017-11-22 16:16:55 -05:00
|
|
|
SelectionContext {
|
|
|
|
infcx,
|
2021-07-07 10:56:26 -05:00
|
|
|
freshener: infcx.freshener_keep_static(),
|
2020-02-08 19:14:50 +01:00
|
|
|
intercrate: false,
|
2018-02-01 17:23:48 -05:00
|
|
|
intercrate_ambiguity_causes: None,
|
2018-02-10 14:34:46 -05:00
|
|
|
allow_negative_impls,
|
2018-04-19 02:28:03 -05:00
|
|
|
query_mode: TraitQueryMode::Standard,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
pub fn with_query_mode(
|
2019-06-14 00:48:52 +03:00
|
|
|
infcx: &'cx InferCtxt<'cx, 'tcx>,
|
2018-09-07 09:34:09 -04:00
|
|
|
query_mode: TraitQueryMode,
|
2019-06-14 00:48:52 +03:00
|
|
|
) -> SelectionContext<'cx, 'tcx> {
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!(?query_mode, "with_query_mode");
|
2018-04-19 02:28:03 -05:00
|
|
|
SelectionContext {
|
|
|
|
infcx,
|
2021-07-07 10:56:26 -05:00
|
|
|
freshener: infcx.freshener_keep_static(),
|
2020-02-08 19:14:50 +01:00
|
|
|
intercrate: false,
|
2018-04-19 02:28:03 -05:00
|
|
|
intercrate_ambiguity_causes: None,
|
|
|
|
allow_negative_impls: false,
|
|
|
|
query_mode,
|
2014-09-18 11:08:04 -04:00
|
|
|
}
|
2014-09-12 10:53:35 -04:00
|
|
|
}
|
|
|
|
|
2018-01-26 17:21:43 -05:00
|
|
|
/// Enables tracking of intercrate ambiguity causes. These are
|
|
|
|
/// used in coherence to give improved diagnostics. We don't do
|
|
|
|
/// this until we detect a coherence error because it can lead to
|
|
|
|
/// false overflow results (#47139) and because it costs
|
|
|
|
/// computation time.
|
|
|
|
pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) {
|
2020-02-08 19:14:50 +01:00
|
|
|
assert!(self.intercrate);
|
2018-01-26 17:21:43 -05:00
|
|
|
assert!(self.intercrate_ambiguity_causes.is_none());
|
|
|
|
self.intercrate_ambiguity_causes = Some(vec![]);
|
|
|
|
debug!("selcx: enable_tracking_intercrate_ambiguity_causes");
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Gets the intercrate ambiguity causes collected since tracking
|
|
|
|
/// was enabled and disables tracking at the same time. If
|
|
|
|
/// tracking is not enabled, just returns an empty vector.
|
|
|
|
pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec<IntercrateAmbiguityCause> {
|
2020-02-08 19:14:50 +01:00
|
|
|
assert!(self.intercrate);
|
2020-11-06 13:24:55 -08:00
|
|
|
self.intercrate_ambiguity_causes.take().unwrap_or_default()
|
2018-01-26 17:21:43 -05:00
|
|
|
}
|
|
|
|
|
2019-06-14 00:48:52 +03:00
|
|
|
pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> {
|
2014-12-07 11:10:48 -05:00
|
|
|
self.infcx
|
|
|
|
}
|
|
|
|
|
2019-06-14 00:48:52 +03:00
|
|
|
pub fn tcx(&self) -> TyCtxt<'tcx> {
|
2014-09-12 10:53:35 -04:00
|
|
|
self.infcx.tcx
|
|
|
|
}
|
|
|
|
|
2021-09-20 14:23:21 -05:00
|
|
|
pub fn is_intercrate(&self) -> bool {
|
|
|
|
self.intercrate
|
|
|
|
}
|
|
|
|
|
2014-09-12 10:53:35 -04:00
|
|
|
///////////////////////////////////////////////////////////////////////////
|
|
|
|
// Selection
|
|
|
|
//
|
|
|
|
// The selection phase tries to identify *how* an obligation will
|
|
|
|
// be resolved. For example, it will identify which impl or
|
|
|
|
// parameter bound is to be used. The process can be inconclusive
|
|
|
|
// if the self type in the obligation is not fully inferred. Selection
|
|
|
|
// can result in an error in one of two ways:
|
|
|
|
//
|
|
|
|
// 1. If no applicable impl or parameter bound can be found.
|
|
|
|
// 2. If the output type parameters in the obligation do not match
|
|
|
|
// those specified by the impl/bound. For example, if the obligation
|
2019-05-17 02:20:14 +01:00
|
|
|
// is `Vec<Foo>: Iterable<Bar>`, but the impl specifies
|
2014-09-12 10:53:35 -04:00
|
|
|
// `impl<T> Iterable<T> for Vec<T>`, than an error would result.
|
|
|
|
|
2015-02-02 11:52:08 -05:00
|
|
|
/// Attempts to satisfy the obligation. If successful, this will affect the surrounding
|
|
|
|
/// type environment by performing unification.
|
2020-10-11 11:37:56 +01:00
|
|
|
#[instrument(level = "debug", skip(self))]
|
2018-09-07 09:34:09 -04:00
|
|
|
pub fn select(
|
|
|
|
&mut self,
|
|
|
|
obligation: &TraitObligation<'tcx>,
|
|
|
|
) -> SelectionResult<'tcx, Selection<'tcx>> {
|
2021-10-01 13:05:17 +00:00
|
|
|
let candidate = match self.select_from_obligation(obligation) {
|
2018-04-19 03:15:36 -05:00
|
|
|
Err(SelectionError::Overflow) => {
|
|
|
|
// In standard mode, overflow must have been caught and reported
|
|
|
|
// earlier.
|
|
|
|
assert!(self.query_mode == TraitQueryMode::Canonical);
|
|
|
|
return Err(SelectionError::Overflow);
|
2018-09-07 09:34:09 -04:00
|
|
|
}
|
2021-10-01 13:05:17 +00:00
|
|
|
Err(SelectionError::Ambiguous(_)) => {
|
|
|
|
return Ok(None);
|
|
|
|
}
|
2018-09-07 09:34:09 -04:00
|
|
|
Err(e) => {
|
|
|
|
return Err(e);
|
|
|
|
}
|
|
|
|
Ok(None) => {
|
|
|
|
return Ok(None);
|
|
|
|
}
|
|
|
|
Ok(Some(candidate)) => candidate,
|
2017-01-11 15:58:37 +08:00
|
|
|
};
|
|
|
|
|
2018-04-05 12:29:18 -05:00
|
|
|
match self.confirm_candidate(obligation, candidate) {
|
2018-04-19 03:15:36 -05:00
|
|
|
Err(SelectionError::Overflow) => {
|
|
|
|
assert!(self.query_mode == TraitQueryMode::Canonical);
|
2018-08-10 18:13:43 +01:00
|
|
|
Err(SelectionError::Overflow)
|
2018-09-07 09:34:09 -04:00
|
|
|
}
|
2018-04-05 12:29:18 -05:00
|
|
|
Err(e) => Err(e),
|
2020-07-22 22:43:18 +01:00
|
|
|
Ok(candidate) => {
|
2021-12-19 22:01:48 -05:00
|
|
|
debug!(?candidate, "confirmed");
|
2020-07-22 22:43:18 +01:00
|
|
|
Ok(Some(candidate))
|
|
|
|
}
|
2018-04-05 12:29:18 -05:00
|
|
|
}
|
2014-09-12 10:53:35 -04:00
|
|
|
}
|
|
|
|
|
2021-10-01 13:05:17 +00:00
|
|
|
crate fn select_from_obligation(
|
|
|
|
&mut self,
|
|
|
|
obligation: &TraitObligation<'tcx>,
|
|
|
|
) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
|
|
|
|
debug_assert!(!obligation.predicate.has_escaping_bound_vars());
|
|
|
|
|
|
|
|
let pec = &ProvisionalEvaluationCache::default();
|
|
|
|
let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation);
|
|
|
|
|
|
|
|
self.candidate_from_obligation(&stack)
|
|
|
|
}
|
|
|
|
|
2014-09-12 10:53:35 -04:00
|
|
|
///////////////////////////////////////////////////////////////////////////
|
|
|
|
// EVALUATION
|
|
|
|
//
|
2014-10-17 08:51:43 -04:00
|
|
|
// Tests whether an obligation can be selected or whether an impl
|
|
|
|
// can be applied to particular types. It skips the "confirmation"
|
|
|
|
// step and hence completely ignores output type parameters.
|
2014-10-09 17:19:50 -04:00
|
|
|
//
|
2014-10-25 23:10:16 -04:00
|
|
|
// The result is "true" if the obligation *may* hold and "false" if
|
2014-10-09 17:19:50 -04:00
|
|
|
// we can be sure it does not.
|
2014-09-12 10:53:35 -04:00
|
|
|
|
2014-11-25 21:17:11 -05:00
|
|
|
/// Evaluates whether the obligation `obligation` can be satisfied (by any means).
|
2018-09-07 09:34:09 -04:00
|
|
|
pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!(?obligation, "predicate_may_hold_fatal");
|
2014-09-12 10:53:35 -04:00
|
|
|
|
2018-04-19 02:28:03 -05:00
|
|
|
// This fatal query is a stopgap that should only be used in standard mode,
|
|
|
|
// where we do not expect overflow to be propagated.
|
|
|
|
assert!(self.query_mode == TraitQueryMode::Standard);
|
|
|
|
|
2019-06-04 12:27:56 -04:00
|
|
|
self.evaluate_root_obligation(obligation)
|
2018-04-19 02:28:03 -05:00
|
|
|
.expect("Overflow should be caught earlier in standard query mode")
|
|
|
|
.may_apply()
|
2014-09-18 11:08:04 -04:00
|
|
|
}
|
|
|
|
|
2019-06-04 12:27:56 -04:00
|
|
|
/// Evaluates whether the obligation `obligation` can be satisfied
|
|
|
|
/// and returns an `EvaluationResult`. This is meant for the
|
|
|
|
/// *initial* call.
|
|
|
|
pub fn evaluate_root_obligation(
|
2018-09-07 09:34:09 -04:00
|
|
|
&mut self,
|
|
|
|
obligation: &PredicateObligation<'tcx>,
|
|
|
|
) -> Result<EvaluationResult, OverflowError> {
|
2018-10-16 05:42:18 -04:00
|
|
|
self.evaluation_probe(|this| {
|
2019-06-06 13:32:00 -04:00
|
|
|
this.evaluate_predicate_recursively(
|
2019-06-10 15:36:38 -04:00
|
|
|
TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
|
2019-06-06 13:32:00 -04:00
|
|
|
obligation.clone(),
|
|
|
|
)
|
2018-10-16 05:42:18 -04:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
fn evaluation_probe(
|
|
|
|
&mut self,
|
|
|
|
op: impl FnOnce(&mut Self) -> Result<EvaluationResult, OverflowError>,
|
|
|
|
) -> Result<EvaluationResult, OverflowError> {
|
|
|
|
self.infcx.probe(|snapshot| -> Result<EvaluationResult, OverflowError> {
|
|
|
|
let result = op(self)?;
|
move leak-check to during coherence, candidate eval
In particular, it no longer occurs during the subtyping check. This is
important for enabling lazy normalization, because the subtyping check
will be producing sub-obligations that could affect its results.
Consider an example like
for<'a> fn(<&'a as Mirror>::Item) =
fn(&'b u8)
where `<T as Mirror>::Item = T` for all `T`. We will wish to produce a
new subobligation like
<'!1 as Mirror>::Item = &'b u8
This will, after being solved, ultimately yield a constraint that `'!1
= 'b` which will fail. But with the leak-check being performed on
subtyping, there is no opportunity to normalize `<'!1 as
Mirror>::Item` (unless we invoke that normalization directly from
within subtyping, and I would prefer that subtyping and unification
are distinct operations rather than part of the trait solving stack).
The reason to keep the leak check during coherence and trait
evaluation is partly for backwards compatibility. The coherence change
permits impls for `fn(T)` and `fn(&T)` to co-exist, and the trait
evaluation change means that we can distinguish those two cases
without ambiguity errors. It also avoids recreating #57639, where we
were incorrectly choosing a where clause that would have failed the
leak check over the impl which succeeds.
The other reason to keep the leak check in those places is that I
think it is actually close to the model we want. To the point, I think
the trait solver ought to have the job of "breaking down"
higher-ranked region obligation like ``!1: '2` into into region
obligations that operate on things in the root universe, at which
point they should be handed off to polonius. The leak check isn't
*really* doing that -- these obligations are still handed to the
region solver to process -- but if/when we do adopt that model, the
decision to pass/fail would be happening in roughly this part of the
code.
This change had somewhat more side-effects than I anticipated. It
seems like there are cases where the leak-check was not being enforced
during method proving and trait selection. I haven't quite tracked
this down but I think it ought to be documented, so that we know what
precisely we are committing to.
One surprising test was `issue-30786.rs`. The behavior there seems a
bit "fishy" to me, but the problem is not related to the leak check
change as far as I can tell, but more to do with the closure signature
inference code and perhaps the associated type projection, which
together seem to be conspiring to produce an unexpected
signature. Nonetheless, it is an example of where changing the
leak-check can have some unexpected consequences: we're now failing to
resolve a method earlier than we were, which suggests we might change
some method resolutions that would have been ambiguous to be
successful.
TODO:
* figure out remainig test failures
* add new coherence tests for the patterns we ARE disallowing
2020-05-20 10:19:36 +00:00
|
|
|
|
|
|
|
match self.infcx.leak_check(true, snapshot) {
|
|
|
|
Ok(()) => {}
|
|
|
|
Err(_) => return Ok(EvaluatedToErr),
|
|
|
|
}
|
|
|
|
|
2018-11-20 10:24:38 -05:00
|
|
|
match self.infcx.region_constraints_added_in_snapshot(snapshot) {
|
|
|
|
None => Ok(result),
|
|
|
|
Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)),
|
2018-10-16 05:42:18 -04:00
|
|
|
}
|
2018-09-07 09:34:09 -04:00
|
|
|
})
|
2018-03-08 18:30:37 -06:00
|
|
|
}
|
|
|
|
|
2015-11-15 20:11:42 +02:00
|
|
|
/// Evaluates the predicates in `predicates` recursively. Note that
|
|
|
|
/// this applies projections in the predicates, and therefore
|
|
|
|
/// is run within an inference probe.
|
2021-08-20 13:36:04 +00:00
|
|
|
#[instrument(skip(self, stack), level = "debug")]
|
2019-06-16 12:33:21 +03:00
|
|
|
fn evaluate_predicates_recursively<'o, I>(
|
2018-09-07 09:34:09 -04:00
|
|
|
&mut self,
|
|
|
|
stack: TraitObligationStackList<'o, 'tcx>,
|
|
|
|
predicates: I,
|
|
|
|
) -> Result<EvaluationResult, OverflowError>
|
|
|
|
where
|
2020-07-22 22:43:18 +01:00
|
|
|
I: IntoIterator<Item = PredicateObligation<'tcx>> + std::fmt::Debug,
|
2015-01-02 11:39:47 -05:00
|
|
|
{
|
|
|
|
let mut result = EvaluatedToOk;
|
|
|
|
for obligation in predicates {
|
2018-12-20 04:02:12 -05:00
|
|
|
let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?;
|
2017-06-30 14:18:04 +03:00
|
|
|
if let EvaluatedToErr = eval {
|
|
|
|
// fast-path - EvaluatedToErr is the top of the lattice,
|
|
|
|
// so we don't need to look on the other predicates.
|
2018-04-05 12:29:18 -05:00
|
|
|
return Ok(EvaluatedToErr);
|
2017-06-30 14:18:04 +03:00
|
|
|
} else {
|
|
|
|
result = cmp::max(result, eval);
|
2015-01-02 11:39:47 -05:00
|
|
|
}
|
|
|
|
}
|
2018-04-05 12:29:18 -05:00
|
|
|
Ok(result)
|
2015-01-02 11:39:47 -05:00
|
|
|
}
|
|
|
|
|
2020-10-11 11:37:56 +01:00
|
|
|
#[instrument(
|
|
|
|
level = "debug",
|
|
|
|
skip(self, previous_stack),
|
|
|
|
fields(previous_stack = ?previous_stack.head())
|
|
|
|
)]
|
2018-09-07 09:34:09 -04:00
|
|
|
fn evaluate_predicate_recursively<'o>(
|
|
|
|
&mut self,
|
|
|
|
previous_stack: TraitObligationStackList<'o, 'tcx>,
|
2018-12-19 23:38:00 -05:00
|
|
|
obligation: PredicateObligation<'tcx>,
|
2018-09-07 09:34:09 -04:00
|
|
|
) -> Result<EvaluationResult, OverflowError> {
|
2020-08-06 14:37:32 -07:00
|
|
|
// `previous_stack` stores a `TraitObligation`, while `obligation` is
|
2019-05-17 02:20:14 +01:00
|
|
|
// a `PredicateObligation`. These are distinct types, so we can't
|
|
|
|
// use any `Option` combinator method that would force them to be
|
|
|
|
// the same.
|
2019-01-02 21:19:03 -05:00
|
|
|
match previous_stack.head() {
|
|
|
|
Some(h) => self.check_recursion_limit(&obligation, h.obligation)?,
|
2019-12-22 17:42:04 -05:00
|
|
|
None => self.check_recursion_limit(&obligation, &obligation)?,
|
2019-01-02 21:19:03 -05:00
|
|
|
}
|
2014-12-07 11:10:48 -05:00
|
|
|
|
2020-10-11 11:37:56 +01:00
|
|
|
let result = ensure_sufficient_stack(|| {
|
2021-01-07 11:20:28 -05:00
|
|
|
let bound_predicate = obligation.predicate.kind();
|
2020-10-07 20:02:06 -04:00
|
|
|
match bound_predicate.skip_binder() {
|
2021-07-22 21:56:07 +08:00
|
|
|
ty::PredicateKind::Trait(t) => {
|
2020-10-16 14:04:11 -04:00
|
|
|
let t = bound_predicate.rebind(t);
|
2020-09-18 11:09:00 -04:00
|
|
|
debug_assert!(!t.has_escaping_bound_vars());
|
|
|
|
let obligation = obligation.with(t);
|
|
|
|
self.evaluate_trait_predicate_recursively(previous_stack, obligation)
|
|
|
|
}
|
2014-12-07 11:10:48 -05:00
|
|
|
|
2021-01-07 11:20:28 -05:00
|
|
|
ty::PredicateKind::Subtype(p) => {
|
2020-10-16 14:04:11 -04:00
|
|
|
let p = bound_predicate.rebind(p);
|
2020-09-18 11:09:00 -04:00
|
|
|
// Does this code ever run?
|
|
|
|
match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
|
|
|
|
Some(Ok(InferOk { mut obligations, .. })) => {
|
|
|
|
self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
|
|
|
|
self.evaluate_predicates_recursively(
|
2020-11-21 07:06:16 -05:00
|
|
|
previous_stack,
|
|
|
|
obligations.into_iter(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
Some(Err(_)) => Ok(EvaluatedToErr),
|
|
|
|
None => Ok(EvaluatedToAmbig),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
ty::PredicateKind::Coerce(p) => {
|
|
|
|
let p = bound_predicate.rebind(p);
|
|
|
|
// Does this code ever run?
|
|
|
|
match self.infcx.coerce_predicate(&obligation.cause, obligation.param_env, p) {
|
|
|
|
Some(Ok(InferOk { mut obligations, .. })) => {
|
|
|
|
self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
|
|
|
|
self.evaluate_predicates_recursively(
|
2020-09-18 11:09:00 -04:00
|
|
|
previous_stack,
|
|
|
|
obligations.into_iter(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
Some(Err(_)) => Ok(EvaluatedToErr),
|
|
|
|
None => Ok(EvaluatedToAmbig),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-07 11:20:28 -05:00
|
|
|
ty::PredicateKind::WellFormed(arg) => match wf::obligations(
|
2020-09-18 11:09:00 -04:00
|
|
|
self.infcx,
|
|
|
|
obligation.param_env,
|
|
|
|
obligation.cause.body_id,
|
2020-07-22 22:43:18 +01:00
|
|
|
obligation.recursion_depth + 1,
|
2020-09-18 11:09:00 -04:00
|
|
|
arg,
|
|
|
|
obligation.cause.span,
|
|
|
|
) {
|
|
|
|
Some(mut obligations) => {
|
2018-12-20 04:02:12 -05:00
|
|
|
self.add_depth(obligations.iter_mut(), obligation.recursion_depth);
|
2020-07-22 22:43:18 +01:00
|
|
|
self.evaluate_predicates_recursively(previous_stack, obligations)
|
2018-09-07 09:34:09 -04:00
|
|
|
}
|
2018-04-05 12:29:18 -05:00
|
|
|
None => Ok(EvaluatedToAmbig),
|
2020-09-18 11:09:00 -04:00
|
|
|
},
|
2017-03-09 21:47:09 -05:00
|
|
|
|
2021-05-08 17:06:37 -04:00
|
|
|
ty::PredicateKind::TypeOutlives(pred) => {
|
2021-11-28 14:31:22 -05:00
|
|
|
// A global type with no late-bound regions can only
|
|
|
|
// contain the "'static" lifetime (any other lifetime
|
|
|
|
// would either be late-bound or local), so it is guaranteed
|
|
|
|
// to outlive any other lifetime
|
2022-01-12 03:19:52 +00:00
|
|
|
if pred.0.is_global() && !pred.0.has_late_bound_regions() {
|
2021-05-08 17:06:37 -04:00
|
|
|
Ok(EvaluatedToOk)
|
|
|
|
} else {
|
|
|
|
Ok(EvaluatedToOkModuloRegions)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
ty::PredicateKind::RegionOutlives(..) => {
|
2020-09-18 11:09:00 -04:00
|
|
|
// We do not consider region relationships when evaluating trait matches.
|
|
|
|
Ok(EvaluatedToOkModuloRegions)
|
2020-05-23 18:28:50 +02:00
|
|
|
}
|
2015-08-07 09:30:19 -04:00
|
|
|
|
2021-01-07 11:20:28 -05:00
|
|
|
ty::PredicateKind::ObjectSafe(trait_def_id) => {
|
2020-09-18 11:09:00 -04:00
|
|
|
if self.tcx().is_object_safe(trait_def_id) {
|
|
|
|
Ok(EvaluatedToOk)
|
|
|
|
} else {
|
|
|
|
Ok(EvaluatedToErr)
|
|
|
|
}
|
2015-08-07 09:30:19 -04:00
|
|
|
}
|
2014-12-17 14:16:28 -05:00
|
|
|
|
2021-01-07 11:20:28 -05:00
|
|
|
ty::PredicateKind::Projection(data) => {
|
2020-10-16 14:04:11 -04:00
|
|
|
let data = bound_predicate.rebind(data);
|
2020-09-18 11:09:00 -04:00
|
|
|
let project_obligation = obligation.with(data);
|
|
|
|
match project::poly_project_and_unify_type(self, &project_obligation) {
|
|
|
|
Ok(Ok(Some(mut subobligations))) => {
|
2021-10-09 11:29:39 -05:00
|
|
|
'compute_res: {
|
2022-03-16 20:12:30 +08:00
|
|
|
// If we've previously marked this projection as 'complete', then
|
2021-10-09 11:29:39 -05:00
|
|
|
// use the final cached result (either `EvaluatedToOk` or
|
|
|
|
// `EvaluatedToOkModuloRegions`), and skip re-evaluating the
|
|
|
|
// sub-obligations.
|
|
|
|
if let Some(key) =
|
|
|
|
ProjectionCacheKey::from_poly_projection_predicate(self, data)
|
|
|
|
{
|
|
|
|
if let Some(cached_res) = self
|
|
|
|
.infcx
|
|
|
|
.inner
|
|
|
|
.borrow_mut()
|
|
|
|
.projection_cache()
|
|
|
|
.is_complete(key)
|
|
|
|
{
|
|
|
|
break 'compute_res Ok(cached_res);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
self.add_depth(
|
|
|
|
subobligations.iter_mut(),
|
|
|
|
obligation.recursion_depth,
|
|
|
|
);
|
|
|
|
let res = self.evaluate_predicates_recursively(
|
|
|
|
previous_stack,
|
|
|
|
subobligations,
|
|
|
|
);
|
2022-03-01 18:34:35 -03:00
|
|
|
if let Ok(eval_rslt) = res
|
|
|
|
&& (eval_rslt == EvaluatedToOk || eval_rslt == EvaluatedToOkModuloRegions)
|
|
|
|
&& let Some(key) =
|
|
|
|
ProjectionCacheKey::from_poly_projection_predicate(
|
|
|
|
self, data,
|
|
|
|
)
|
|
|
|
{
|
|
|
|
// If the result is something that we can cache, then mark this
|
|
|
|
// entry as 'complete'. This will allow us to skip evaluating the
|
|
|
|
// suboligations at all the next time we evaluate the projection
|
|
|
|
// predicate.
|
|
|
|
self.infcx
|
|
|
|
.inner
|
|
|
|
.borrow_mut()
|
|
|
|
.projection_cache()
|
|
|
|
.complete(key, eval_rslt);
|
2021-10-09 11:29:39 -05:00
|
|
|
}
|
|
|
|
res
|
|
|
|
}
|
2017-08-20 19:16:36 +03:00
|
|
|
}
|
2020-09-18 11:09:00 -04:00
|
|
|
Ok(Ok(None)) => Ok(EvaluatedToAmbig),
|
2020-10-08 21:49:36 +01:00
|
|
|
Ok(Err(project::InProgress)) => Ok(EvaluatedToRecur),
|
2020-09-18 11:09:00 -04:00
|
|
|
Err(_) => Ok(EvaluatedToErr),
|
2018-09-07 09:34:09 -04:00
|
|
|
}
|
2015-10-20 18:23:46 +03:00
|
|
|
}
|
2016-04-06 00:20:59 -07:00
|
|
|
|
2021-01-07 11:20:28 -05:00
|
|
|
ty::PredicateKind::ClosureKind(_, closure_substs, kind) => {
|
2020-09-18 11:09:00 -04:00
|
|
|
match self.infcx.closure_kind(closure_substs) {
|
|
|
|
Some(closure_kind) => {
|
|
|
|
if closure_kind.extends(kind) {
|
|
|
|
Ok(EvaluatedToOk)
|
|
|
|
} else {
|
|
|
|
Ok(EvaluatedToErr)
|
|
|
|
}
|
2016-04-06 00:20:59 -07:00
|
|
|
}
|
2020-09-18 11:09:00 -04:00
|
|
|
None => Ok(EvaluatedToAmbig),
|
2018-09-07 09:34:09 -04:00
|
|
|
}
|
2016-04-06 00:20:59 -07:00
|
|
|
}
|
2017-08-07 08:08:53 +03:00
|
|
|
|
2021-07-19 13:52:43 +02:00
|
|
|
ty::PredicateKind::ConstEvaluatable(uv) => {
|
2020-09-18 11:09:00 -04:00
|
|
|
match const_evaluatable::is_const_evaluatable(
|
|
|
|
self.infcx,
|
2021-07-19 13:52:43 +02:00
|
|
|
uv,
|
2020-09-18 11:09:00 -04:00
|
|
|
obligation.param_env,
|
|
|
|
obligation.cause.span,
|
|
|
|
) {
|
|
|
|
Ok(()) => Ok(EvaluatedToOk),
|
2021-03-02 15:47:06 +00:00
|
|
|
Err(NotConstEvaluatable::MentionsInfer) => Ok(EvaluatedToAmbig),
|
|
|
|
Err(NotConstEvaluatable::MentionsParam) => Ok(EvaluatedToErr),
|
2020-09-18 11:09:00 -04:00
|
|
|
Err(_) => Ok(EvaluatedToErr),
|
|
|
|
}
|
2020-08-06 22:12:21 +02:00
|
|
|
}
|
2020-02-29 10:03:04 +13:00
|
|
|
|
2021-01-07 11:20:28 -05:00
|
|
|
ty::PredicateKind::ConstEquate(c1, c2) => {
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!(?c1, ?c2, "evaluate_predicate_recursively: equating consts");
|
2020-09-18 11:09:00 -04:00
|
|
|
|
2021-08-25 10:21:39 +01:00
|
|
|
if self.tcx().features().generic_const_exprs {
|
2021-05-19 21:23:32 +02:00
|
|
|
// FIXME: we probably should only try to unify abstract constants
|
|
|
|
// if the constants depend on generic parameters.
|
|
|
|
//
|
|
|
|
// Let's just see where this breaks :shrug:
|
|
|
|
if let (ty::ConstKind::Unevaluated(a), ty::ConstKind::Unevaluated(b)) =
|
2022-02-02 14:24:45 +11:00
|
|
|
(c1.val(), c2.val())
|
2021-05-19 21:23:32 +02:00
|
|
|
{
|
2021-08-02 08:47:15 +02:00
|
|
|
if self.infcx.try_unify_abstract_consts(a.shrink(), b.shrink()) {
|
2021-05-19 21:23:32 +02:00
|
|
|
return Ok(EvaluatedToOk);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-02 14:24:45 +11:00
|
|
|
let evaluate = |c: ty::Const<'tcx>| {
|
|
|
|
if let ty::ConstKind::Unevaluated(unevaluated) = c.val() {
|
2020-09-18 11:09:00 -04:00
|
|
|
self.infcx
|
|
|
|
.const_eval_resolve(
|
|
|
|
obligation.param_env,
|
2021-03-13 16:31:38 +01:00
|
|
|
unevaluated,
|
2020-09-18 11:09:00 -04:00
|
|
|
Some(obligation.cause.span),
|
|
|
|
)
|
2022-02-02 14:24:45 +11:00
|
|
|
.map(|val| ty::Const::from_value(self.tcx(), val, c.ty()))
|
2020-09-18 11:09:00 -04:00
|
|
|
} else {
|
|
|
|
Ok(c)
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
match (evaluate(c1), evaluate(c2)) {
|
|
|
|
(Ok(c1), Ok(c2)) => {
|
|
|
|
match self
|
|
|
|
.infcx()
|
|
|
|
.at(&obligation.cause, obligation.param_env)
|
|
|
|
.eq(c1, c2)
|
|
|
|
{
|
|
|
|
Ok(_) => Ok(EvaluatedToOk),
|
|
|
|
Err(_) => Ok(EvaluatedToErr),
|
|
|
|
}
|
|
|
|
}
|
2022-01-22 18:49:12 -06:00
|
|
|
(Err(ErrorHandled::Reported(_)), _)
|
|
|
|
| (_, Err(ErrorHandled::Reported(_))) => Ok(EvaluatedToErr),
|
2020-09-18 11:09:00 -04:00
|
|
|
(Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
|
|
|
|
span_bug!(
|
|
|
|
obligation.cause.span(self.tcx()),
|
|
|
|
"ConstEquate: const_eval_resolve returned an unexpected error"
|
2020-05-07 12:45:15 +02:00
|
|
|
)
|
2020-02-29 10:03:04 +13:00
|
|
|
}
|
2020-09-18 11:09:00 -04:00
|
|
|
(Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
|
2021-05-19 21:23:32 +02:00
|
|
|
if c1.has_infer_types_or_consts() || c2.has_infer_types_or_consts() {
|
|
|
|
Ok(EvaluatedToAmbig)
|
|
|
|
} else {
|
|
|
|
// Two different constants using generic parameters ~> error.
|
|
|
|
Ok(EvaluatedToErr)
|
|
|
|
}
|
2020-09-18 11:09:00 -04:00
|
|
|
}
|
2020-05-07 12:45:15 +02:00
|
|
|
}
|
2020-02-29 10:03:04 +13:00
|
|
|
}
|
2021-01-07 11:20:28 -05:00
|
|
|
ty::PredicateKind::TypeWellFormedFromEnv(..) => {
|
2020-09-18 11:09:00 -04:00
|
|
|
bug!("TypeWellFormedFromEnv is only used for chalk")
|
|
|
|
}
|
2020-02-29 10:03:04 +13:00
|
|
|
}
|
2020-10-11 11:37:56 +01:00
|
|
|
});
|
|
|
|
|
2021-05-31 13:22:40 -05:00
|
|
|
debug!("finished: {:?} from {:?}", result, obligation);
|
2020-10-11 11:37:56 +01:00
|
|
|
|
|
|
|
result
|
2014-12-07 11:10:48 -05:00
|
|
|
}
|
|
|
|
|
2021-08-20 13:36:04 +00:00
|
|
|
#[instrument(skip(self, previous_stack), level = "debug")]
|
2018-09-07 09:34:09 -04:00
|
|
|
fn evaluate_trait_predicate_recursively<'o>(
|
|
|
|
&mut self,
|
|
|
|
previous_stack: TraitObligationStackList<'o, 'tcx>,
|
|
|
|
mut obligation: TraitObligation<'tcx>,
|
|
|
|
) -> Result<EvaluationResult, OverflowError> {
|
2020-02-08 19:14:50 +01:00
|
|
|
if !self.intercrate
|
2022-01-12 03:19:52 +00:00
|
|
|
&& obligation.is_global()
|
|
|
|
&& obligation.param_env.caller_bounds().iter().all(|bound| bound.needs_subst())
|
2018-09-07 09:34:09 -04:00
|
|
|
{
|
2018-05-06 22:48:56 +01:00
|
|
|
// If a param env has no global bounds, global obligations do not
|
|
|
|
// depend on its particular value in order to work, so we can clear
|
|
|
|
// out the param env and get better caching.
|
2021-08-20 13:36:04 +00:00
|
|
|
debug!("in global");
|
2018-02-10 13:18:02 -05:00
|
|
|
obligation.param_env = obligation.param_env.without_caller_bounds();
|
2017-06-23 00:27:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
let stack = self.push_stack(previous_stack, &obligation);
|
2021-12-12 12:34:46 +08:00
|
|
|
let mut fresh_trait_pred = stack.fresh_trait_pred;
|
|
|
|
let mut param_env = obligation.param_env;
|
|
|
|
|
|
|
|
fresh_trait_pred = fresh_trait_pred.map_bound(|mut pred| {
|
2021-12-21 13:23:59 +08:00
|
|
|
pred.remap_constness(self.tcx(), &mut param_env);
|
2021-12-12 12:34:46 +08:00
|
|
|
pred
|
|
|
|
});
|
2020-10-11 11:37:56 +01:00
|
|
|
|
2021-12-12 12:34:46 +08:00
|
|
|
debug!(?fresh_trait_pred);
|
2020-10-11 11:37:56 +01:00
|
|
|
|
2021-12-12 12:34:46 +08:00
|
|
|
if let Some(result) = self.check_evaluation_cache(param_env, fresh_trait_pred) {
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!(?result, "CACHE HIT");
|
2018-04-05 12:29:18 -05:00
|
|
|
return Ok(result);
|
2015-10-18 19:15:57 +03:00
|
|
|
}
|
2014-10-17 08:51:43 -04:00
|
|
|
|
2021-12-12 12:34:46 +08:00
|
|
|
if let Some(result) = stack.cache().get_provisional(fresh_trait_pred) {
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!(?result, "PROVISIONAL CACHE HIT");
|
have on_completion record subcycles
Rework `on_completion` method so that it removes all
provisional cache entries that are "below" a completed
node (while leaving those entries that are not below
the node).
This corrects an imprecise result that could in turn lead
to an incremental compilation failure. Under the old
scheme, if you had:
* A depends on...
* B depends on A
* C depends on...
* D depends on C
* T: 'static
then the provisional results for A, B, C, and D would all
be entangled. Thus, if A was `EvaluatedToOkModuloRegions`
(because of that final condition), then the result for C and
D would also be demoted to "ok modulo regions".
In reality, though, the result for C depends only on C and itself,
and is not dependent on regions. If we happen to evaluate the
cycle starting from C, we would never reach A, and hence the
result would be "ok".
Under the new scheme, the provisional results for C and D
are moved to the permanent cache immediately and are not affected
by the result of A.
2021-05-11 05:40:42 -04:00
|
|
|
stack.update_reached_depth(result.reached_depth);
|
|
|
|
return Ok(result.result);
|
2019-06-11 19:05:08 -04:00
|
|
|
}
|
|
|
|
|
2019-06-10 15:35:37 -04:00
|
|
|
// Check if this is a match for something already on the
|
|
|
|
// stack. If so, we don't want to insert the result into the
|
|
|
|
// main cache (it is cycle dependent) nor the provisional
|
|
|
|
// cache (which is meant for things that have completed but
|
|
|
|
// for a "backedge" -- this result *is* the backedge).
|
|
|
|
if let Some(cycle_result) = self.check_evaluation_cycle(&stack) {
|
|
|
|
return Ok(cycle_result);
|
|
|
|
}
|
|
|
|
|
2017-07-10 17:10:30 -04:00
|
|
|
let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
|
2018-04-05 12:29:18 -05:00
|
|
|
let result = result?;
|
2014-10-17 08:51:43 -04:00
|
|
|
|
2019-06-11 19:05:08 -04:00
|
|
|
if !result.must_apply_modulo_regions() {
|
|
|
|
stack.cache().on_failure(stack.dfn);
|
|
|
|
}
|
|
|
|
|
2019-06-10 11:46:53 -04:00
|
|
|
let reached_depth = stack.reached_depth.get();
|
|
|
|
if reached_depth >= stack.depth {
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!(?result, "CACHE MISS");
|
2021-12-12 12:34:46 +08:00
|
|
|
self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result);
|
2019-06-11 19:05:08 -04:00
|
|
|
|
Properly track `DepNode`s in trait evaluation provisional cache
Fixes #92987
During evaluation of an auto trait predicate, we may encounter a cycle.
This causes us to store the evaluation result in a special 'provisional
cache;. If we later end up determining that the type can legitimately
implement the auto trait despite the cycle, we remove the entry from
the provisional cache, and insert it into the evaluation cache.
Additionally, trait evaluation creates a special anonymous `DepNode`.
All queries invoked during the predicate evaluation are added as
outoging dependency edges from the `DepNode`. This `DepNode` is then
store in the evaluation cache - if a different query ends up reading
from the cache entry, it will also perform a read of the stored
`DepNode`. As a result, the cached evaluation will still end up
(transitively) incurring all of the same dependencies that it would
if it actually performed the uncached evaluation (e.g. a call to
`type_of` to determine constituent types).
Previously, we did not correctly handle the interaction between the
provisional cache and the created `DepNode`. Storing an evaluation
result in the provisional cache would cause us to lose the `DepNode`
created during the evaluation. If we later moved the entry from the
provisional cache to the evaluation cache, we would use the `DepNode`
associated with the evaluation that caused us to 'complete' the cycle,
not the evaluatoon where we first discovered the cycle. As a result,
future reads from the evaluation cache would miss some incremental
compilation dependencies that would have otherwise been added if the
evaluation was *not* cached.
Under the right circumstances, this could lead to us trying to force
a query with a no-longer-existing `DefPathHash`, since we were missing
the (red) dependency edge that would have caused us to bail out before
attempting forcing.
This commit makes the provisional cache store the `DepNode` create
during the provisional evaluation. When we move an entry from the
provisional cache to the evaluation cache, we create a *new* `DepNode`
that has dependencies going to *both* of the evaluation `DepNodes` we
have available. This ensures that cached reads will incur all of
the necessary dependency edges.
2022-01-18 23:03:55 -05:00
|
|
|
stack.cache().on_completion(
|
|
|
|
stack.dfn,
|
|
|
|
|fresh_trait_pred, provisional_result, provisional_dep_node| {
|
|
|
|
// Create a new `DepNode` that has dependencies on:
|
|
|
|
// * The `DepNode` for the original evaluation that resulted in a provisional cache
|
|
|
|
// entry being crated
|
|
|
|
// * The `DepNode` for the *current* evaluation, which resulted in us completing
|
|
|
|
// provisional caches entries and inserting them into the evaluation cache
|
|
|
|
//
|
|
|
|
// This ensures that when a query reads this entry from the evaluation cache,
|
|
|
|
// it will end up (transitively) dependening on all of the incr-comp dependencies
|
|
|
|
// created during the evaluation of this trait. For example, evaluating a trait
|
|
|
|
// will usually require us to invoke `type_of(field_def_id)` to determine the
|
|
|
|
// constituent types, and we want any queries reading from this evaluation
|
|
|
|
// cache entry to end up with a transitive `type_of(field_def_id`)` dependency.
|
|
|
|
//
|
|
|
|
// By using `in_task`, we're also creating an edge from the *current* query
|
|
|
|
// to the newly-created `combined_dep_node`. This is probably redundant,
|
|
|
|
// but it's better to add too many dep graph edges than to add too few
|
|
|
|
// dep graph edges.
|
|
|
|
let ((), combined_dep_node) = self.in_task(|this| {
|
|
|
|
this.tcx().dep_graph.read_index(provisional_dep_node);
|
|
|
|
this.tcx().dep_graph.read_index(dep_node);
|
|
|
|
});
|
|
|
|
self.insert_evaluation_cache(
|
|
|
|
param_env,
|
|
|
|
fresh_trait_pred,
|
|
|
|
combined_dep_node,
|
|
|
|
provisional_result.max(result),
|
|
|
|
);
|
|
|
|
},
|
|
|
|
);
|
2019-05-01 13:10:01 -04:00
|
|
|
} else {
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!(?result, "PROVISIONAL");
|
2019-05-01 13:10:01 -04:00
|
|
|
debug!(
|
2021-08-20 13:36:04 +00:00
|
|
|
"caching provisionally because {:?} \
|
2019-06-10 11:46:53 -04:00
|
|
|
is a cycle participant (at depth {}, reached depth {})",
|
2021-12-12 12:34:46 +08:00
|
|
|
fresh_trait_pred, stack.depth, reached_depth,
|
2019-05-01 13:10:01 -04:00
|
|
|
);
|
2019-06-11 19:05:08 -04:00
|
|
|
|
Properly track `DepNode`s in trait evaluation provisional cache
Fixes #92987
During evaluation of an auto trait predicate, we may encounter a cycle.
This causes us to store the evaluation result in a special 'provisional
cache;. If we later end up determining that the type can legitimately
implement the auto trait despite the cycle, we remove the entry from
the provisional cache, and insert it into the evaluation cache.
Additionally, trait evaluation creates a special anonymous `DepNode`.
All queries invoked during the predicate evaluation are added as
outoging dependency edges from the `DepNode`. This `DepNode` is then
store in the evaluation cache - if a different query ends up reading
from the cache entry, it will also perform a read of the stored
`DepNode`. As a result, the cached evaluation will still end up
(transitively) incurring all of the same dependencies that it would
if it actually performed the uncached evaluation (e.g. a call to
`type_of` to determine constituent types).
Previously, we did not correctly handle the interaction between the
provisional cache and the created `DepNode`. Storing an evaluation
result in the provisional cache would cause us to lose the `DepNode`
created during the evaluation. If we later moved the entry from the
provisional cache to the evaluation cache, we would use the `DepNode`
associated with the evaluation that caused us to 'complete' the cycle,
not the evaluatoon where we first discovered the cycle. As a result,
future reads from the evaluation cache would miss some incremental
compilation dependencies that would have otherwise been added if the
evaluation was *not* cached.
Under the right circumstances, this could lead to us trying to force
a query with a no-longer-existing `DefPathHash`, since we were missing
the (red) dependency edge that would have caused us to bail out before
attempting forcing.
This commit makes the provisional cache store the `DepNode` create
during the provisional evaluation. When we move an entry from the
provisional cache to the evaluation cache, we create a *new* `DepNode`
that has dependencies going to *both* of the evaluation `DepNodes` we
have available. This ensures that cached reads will incur all of
the necessary dependency edges.
2022-01-18 23:03:55 -05:00
|
|
|
stack.cache().insert_provisional(
|
|
|
|
stack.dfn,
|
|
|
|
reached_depth,
|
|
|
|
fresh_trait_pred,
|
|
|
|
result,
|
|
|
|
dep_node,
|
|
|
|
);
|
2019-05-01 13:10:01 -04:00
|
|
|
}
|
2015-10-18 19:15:57 +03:00
|
|
|
|
2018-04-05 12:29:18 -05:00
|
|
|
Ok(result)
|
2014-10-09 17:19:50 -04:00
|
|
|
}
|
|
|
|
|
2019-06-10 15:35:37 -04:00
|
|
|
/// If there is any previous entry on the stack that precisely
|
|
|
|
/// matches this obligation, then we can assume that the
|
|
|
|
/// obligation is satisfied for now (still all other conditions
|
|
|
|
/// must be met of course). One obvious case this comes up is
|
|
|
|
/// marker traits like `Send`. Think of a linked list:
|
|
|
|
///
|
|
|
|
/// struct List<T> { data: T, next: Option<Box<List<T>>> }
|
|
|
|
///
|
|
|
|
/// `Box<List<T>>` will be `Send` if `T` is `Send` and
|
|
|
|
/// `Option<Box<List<T>>>` is `Send`, and in turn
|
|
|
|
/// `Option<Box<List<T>>>` is `Send` if `Box<List<T>>` is
|
|
|
|
/// `Send`.
|
|
|
|
///
|
|
|
|
/// Note that we do this comparison using the `fresh_trait_ref`
|
|
|
|
/// fields. Because these have all been freshened using
|
|
|
|
/// `self.freshener`, we can be sure that (a) this will not
|
|
|
|
/// affect the inferencer state and (b) that if we see two
|
|
|
|
/// fresh regions with the same index, they refer to the same
|
|
|
|
/// unbound type variable.
|
|
|
|
fn check_evaluation_cycle(
|
|
|
|
&mut self,
|
|
|
|
stack: &TraitObligationStack<'_, 'tcx>,
|
|
|
|
) -> Option<EvaluationResult> {
|
2019-12-22 17:42:04 -05:00
|
|
|
if let Some(cycle_depth) = stack
|
|
|
|
.iter()
|
2019-05-17 02:20:14 +01:00
|
|
|
.skip(1) // Skip top-most frame.
|
2019-12-22 17:42:04 -05:00
|
|
|
.find(|prev| {
|
|
|
|
stack.obligation.param_env == prev.obligation.param_env
|
2021-12-12 12:34:46 +08:00
|
|
|
&& stack.fresh_trait_pred == prev.fresh_trait_pred
|
2019-12-22 17:42:04 -05:00
|
|
|
})
|
2019-06-10 15:35:37 -04:00
|
|
|
.map(|stack| stack.depth)
|
|
|
|
{
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!("evaluate_stack --> recursive at depth {}", cycle_depth);
|
2019-06-10 15:35:37 -04:00
|
|
|
|
|
|
|
// If we have a stack like `A B C D E A`, where the top of
|
|
|
|
// the stack is the final `A`, then this will iterate over
|
|
|
|
// `A, E, D, C, B` -- i.e., all the participants apart
|
|
|
|
// from the cycle head. We mark them as participating in a
|
|
|
|
// cycle. This suppresses caching for those nodes. See
|
|
|
|
// `in_cycle` field for more details.
|
|
|
|
stack.update_reached_depth(cycle_depth);
|
|
|
|
|
|
|
|
// Subtle: when checking for a coinductive cycle, we do
|
|
|
|
// not compare using the "freshened trait refs" (which
|
|
|
|
// have erased regions) but rather the fully explicit
|
|
|
|
// trait refs. This is important because it's only a cycle
|
|
|
|
// if the regions match exactly.
|
|
|
|
let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth);
|
2020-05-11 22:06:41 +02:00
|
|
|
let tcx = self.tcx();
|
2021-07-22 21:56:07 +08:00
|
|
|
let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx));
|
2019-06-10 15:35:37 -04:00
|
|
|
if self.coinductive_match(cycle) {
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!("evaluate_stack --> recursive, coinductive");
|
2019-06-10 15:35:37 -04:00
|
|
|
Some(EvaluatedToOk)
|
|
|
|
} else {
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!("evaluate_stack --> recursive, inductive");
|
2019-06-10 15:35:37 -04:00
|
|
|
Some(EvaluatedToRecur)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
fn evaluate_stack<'o>(
|
|
|
|
&mut self,
|
|
|
|
stack: &TraitObligationStack<'o, 'tcx>,
|
|
|
|
) -> Result<EvaluationResult, OverflowError> {
|
2020-03-23 06:04:03 +02:00
|
|
|
// In intercrate mode, whenever any of the generics are unbound,
|
2014-11-03 14:48:03 -05:00
|
|
|
// there can always be an impl. Even if there are no impls in
|
|
|
|
// this crate, perhaps the type would be unified with
|
|
|
|
// something from another crate that does provide an impl.
|
|
|
|
//
|
2016-02-16 10:36:47 -08:00
|
|
|
// In intra mode, we must still be conservative. The reason is
|
2014-11-03 14:48:03 -05:00
|
|
|
// that we want to avoid cycles. Imagine an impl like:
|
|
|
|
//
|
|
|
|
// impl<T:Eq> Eq for Vec<T>
|
|
|
|
//
|
|
|
|
// and a trait reference like `$0 : Eq` where `$0` is an
|
|
|
|
// unbound variable. When we evaluate this trait-reference, we
|
|
|
|
// will unify `$0` with `Vec<$1>` (for some fresh variable
|
|
|
|
// `$1`), on the condition that `$1 : Eq`. We will then wind
|
|
|
|
// up with many candidates (since that are other `Eq` impls
|
|
|
|
// that apply) and try to winnow things down. This results in
|
2015-01-06 20:53:18 -05:00
|
|
|
// a recursive evaluation that `$1 : Eq` -- as you can
|
2014-11-03 14:48:03 -05:00
|
|
|
// imagine, this is just where we started. To avoid that, we
|
|
|
|
// check for unbound variables and return an ambiguous (hence possible)
|
|
|
|
// match if we've seen this trait before.
|
|
|
|
//
|
|
|
|
// This suffices to allow chains like `FnMut` implemented in
|
|
|
|
// terms of `Fn` etc, but we could probably make this more
|
|
|
|
// precise still.
|
2019-12-22 17:42:04 -05:00
|
|
|
let unbound_input_types =
|
2021-12-12 12:34:46 +08:00
|
|
|
stack.fresh_trait_pred.skip_binder().trait_ref.substs.types().any(|ty| ty.is_fresh());
|
2021-10-15 16:09:04 -03:00
|
|
|
|
2021-10-20 14:12:11 -03:00
|
|
|
if stack.obligation.polarity() != ty::ImplPolarity::Negative {
|
2021-10-15 16:09:04 -03:00
|
|
|
// This check was an imperfect workaround for a bug in the old
|
|
|
|
// intercrate mode; it should be removed when that goes away.
|
|
|
|
if unbound_input_types && self.intercrate {
|
|
|
|
debug!("evaluate_stack --> unbound argument, intercrate --> ambiguous",);
|
|
|
|
// Heuristics: show the diagnostics when there are no candidates in crate.
|
|
|
|
if self.intercrate_ambiguity_causes.is_some() {
|
|
|
|
debug!("evaluate_stack: intercrate_ambiguity_causes is some");
|
|
|
|
if let Ok(candidate_set) = self.assemble_candidates(stack) {
|
|
|
|
if !candidate_set.ambiguous && candidate_set.vec.is_empty() {
|
|
|
|
let trait_ref = stack.obligation.predicate.skip_binder().trait_ref;
|
|
|
|
let self_ty = trait_ref.self_ty();
|
2022-02-16 13:04:48 -05:00
|
|
|
let cause = with_no_trimmed_paths!({
|
2021-10-15 16:09:04 -03:00
|
|
|
IntercrateAmbiguityCause::DownstreamCrate {
|
|
|
|
trait_desc: trait_ref.print_only_trait_path().to_string(),
|
|
|
|
self_desc: if self_ty.has_concrete_skeleton() {
|
|
|
|
Some(self_ty.to_string())
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
},
|
|
|
|
}
|
2020-09-02 10:40:56 +03:00
|
|
|
});
|
|
|
|
|
2021-10-15 16:09:04 -03:00
|
|
|
debug!(?cause, "evaluate_stack: pushing cause");
|
|
|
|
self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
|
|
|
|
}
|
2018-01-26 17:21:43 -05:00
|
|
|
}
|
2017-07-23 22:30:47 +09:00
|
|
|
}
|
2021-10-15 16:09:04 -03:00
|
|
|
return Ok(EvaluatedToAmbig);
|
2017-07-23 22:30:47 +09:00
|
|
|
}
|
2015-10-18 19:15:57 +03:00
|
|
|
}
|
2021-10-15 16:09:04 -03:00
|
|
|
|
2019-12-22 17:42:04 -05:00
|
|
|
if unbound_input_types
|
|
|
|
&& stack.iter().skip(1).any(|prev| {
|
|
|
|
stack.obligation.param_env == prev.obligation.param_env
|
|
|
|
&& self.match_fresh_trait_refs(
|
2021-12-12 12:34:46 +08:00
|
|
|
stack.fresh_trait_pred,
|
|
|
|
prev.fresh_trait_pred,
|
2019-12-22 17:42:04 -05:00
|
|
|
prev.obligation.param_env,
|
|
|
|
)
|
|
|
|
})
|
|
|
|
{
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!("evaluate_stack --> unbound argument, recursive --> giving up",);
|
2018-04-05 12:29:18 -05:00
|
|
|
return Ok(EvaluatedToUnknown);
|
2014-10-09 17:19:50 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
match self.candidate_from_obligation(stack) {
|
2015-10-20 18:23:46 +03:00
|
|
|
Ok(Some(c)) => self.evaluate_candidate(stack, &c),
|
2021-10-01 13:05:17 +00:00
|
|
|
Err(SelectionError::Ambiguous(_)) => Ok(EvaluatedToAmbig),
|
2018-04-05 12:29:18 -05:00
|
|
|
Ok(None) => Ok(EvaluatedToAmbig),
|
2021-10-10 00:44:34 -04:00
|
|
|
Err(Overflow) => Err(OverflowError::Canonical),
|
2021-10-05 18:53:24 +01:00
|
|
|
Err(ErrorReporting) => Err(OverflowError::ErrorReporting),
|
2018-09-07 09:34:09 -04:00
|
|
|
Err(..) => Ok(EvaluatedToErr),
|
2014-09-12 10:53:35 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-06-26 17:23:15 +03:00
|
|
|
/// For defaulted traits, we use a co-inductive strategy to solve, so
|
2019-05-17 02:20:14 +01:00
|
|
|
/// that recursion is ok. This routine returns `true` if the top of the
|
2017-06-26 17:23:15 +03:00
|
|
|
/// stack (`cycle[0]`):
|
2017-12-31 17:17:01 +01:00
|
|
|
///
|
2019-02-08 14:53:55 +01:00
|
|
|
/// - is a defaulted trait,
|
|
|
|
/// - it also appears in the backtrace at some position `X`,
|
2019-08-01 15:13:31 +07:00
|
|
|
/// - all the predicates at positions `X..` between `X` and the top are
|
2017-06-26 17:23:15 +03:00
|
|
|
/// also defaulted traits.
|
2020-11-28 14:52:25 -05:00
|
|
|
pub fn coinductive_match<I>(&mut self, mut cycle: I) -> bool
|
2018-09-07 09:34:09 -04:00
|
|
|
where
|
|
|
|
I: Iterator<Item = ty::Predicate<'tcx>>,
|
2017-06-26 17:23:15 +03:00
|
|
|
{
|
|
|
|
cycle.all(|predicate| self.coinductive_predicate(predicate))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
|
2021-01-07 11:20:28 -05:00
|
|
|
let result = match predicate.kind().skip_binder() {
|
2021-07-22 21:56:07 +08:00
|
|
|
ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
|
2018-09-07 09:34:09 -04:00
|
|
|
_ => false,
|
2017-06-26 17:23:15 +03:00
|
|
|
};
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!(?predicate, ?result, "coinductive_predicate");
|
2017-06-26 17:23:15 +03:00
|
|
|
result
|
|
|
|
}
|
|
|
|
|
2019-05-17 02:20:14 +01:00
|
|
|
/// Further evaluates `candidate` to decide whether all type parameters match and whether nested
|
2019-02-08 14:53:55 +01:00
|
|
|
/// obligations are met. Returns whether `candidate` remains viable after this further
|
2015-10-20 18:23:46 +03:00
|
|
|
/// scrutiny.
|
2020-10-11 11:37:56 +01:00
|
|
|
#[instrument(
|
|
|
|
level = "debug",
|
|
|
|
skip(self, stack),
|
|
|
|
fields(depth = stack.obligation.recursion_depth)
|
|
|
|
)]
|
2018-09-07 09:34:09 -04:00
|
|
|
fn evaluate_candidate<'o>(
|
|
|
|
&mut self,
|
|
|
|
stack: &TraitObligationStack<'o, 'tcx>,
|
|
|
|
candidate: &SelectionCandidate<'tcx>,
|
|
|
|
) -> Result<EvaluationResult, OverflowError> {
|
2021-03-16 19:28:27 -04:00
|
|
|
let mut result = self.evaluation_probe(|this| {
|
2015-10-20 18:23:46 +03:00
|
|
|
let candidate = (*candidate).clone();
|
2018-10-16 05:42:18 -04:00
|
|
|
match this.confirm_candidate(stack.obligation, candidate) {
|
2020-07-22 22:43:18 +01:00
|
|
|
Ok(selection) => {
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!(?selection);
|
2020-07-22 22:43:18 +01:00
|
|
|
this.evaluate_predicates_recursively(
|
|
|
|
stack.list(),
|
|
|
|
selection.nested_obligations().into_iter(),
|
|
|
|
)
|
|
|
|
}
|
2018-09-07 09:34:09 -04:00
|
|
|
Err(..) => Ok(EvaluatedToErr),
|
2014-10-17 08:51:43 -04:00
|
|
|
}
|
2018-04-05 12:29:18 -05:00
|
|
|
})?;
|
2021-03-16 19:28:27 -04:00
|
|
|
|
|
|
|
// If we erased any lifetimes, then we want to use
|
|
|
|
// `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk`
|
|
|
|
// as your final result. The result will be cached using
|
|
|
|
// the freshened trait predicate as a key, so we need
|
|
|
|
// our result to be correct by *any* choice of original lifetimes,
|
|
|
|
// not just the lifetime choice for this particular (non-erased)
|
|
|
|
// predicate.
|
|
|
|
// See issue #80691
|
2021-12-12 12:34:46 +08:00
|
|
|
if stack.fresh_trait_pred.has_erased_regions() {
|
2021-03-16 19:28:27 -04:00
|
|
|
result = result.max(EvaluatedToOkModuloRegions);
|
|
|
|
}
|
|
|
|
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!(?result);
|
2018-04-05 12:29:18 -05:00
|
|
|
Ok(result)
|
2014-10-17 08:51:43 -04:00
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
fn check_evaluation_cache(
|
|
|
|
&self,
|
|
|
|
param_env: ty::ParamEnv<'tcx>,
|
2021-12-12 12:34:46 +08:00
|
|
|
trait_pred: ty::PolyTraitPredicate<'tcx>,
|
2018-09-07 09:34:09 -04:00
|
|
|
) -> Option<EvaluationResult> {
|
2021-09-15 18:17:38 -05:00
|
|
|
// Neither the global nor local cache is aware of intercrate
|
|
|
|
// mode, so don't do any caching. In particular, we might
|
|
|
|
// re-use the same `InferCtxt` with both an intercrate
|
|
|
|
// and non-intercrate `SelectionContext`
|
|
|
|
if self.intercrate {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
2017-07-10 17:10:30 -04:00
|
|
|
let tcx = self.tcx();
|
2017-05-23 04:19:47 -04:00
|
|
|
if self.can_use_global_caches(param_env) {
|
2021-12-12 12:34:46 +08:00
|
|
|
if let Some(res) = tcx.evaluation_cache.get(¶m_env.and(trait_pred), tcx) {
|
2020-08-02 15:03:47 +02:00
|
|
|
return Some(res);
|
2016-04-29 06:00:23 +03:00
|
|
|
}
|
|
|
|
}
|
2021-12-12 12:34:46 +08:00
|
|
|
self.infcx.evaluation_cache.get(¶m_env.and(trait_pred), tcx)
|
2015-10-18 19:15:57 +03:00
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
fn insert_evaluation_cache(
|
|
|
|
&mut self,
|
|
|
|
param_env: ty::ParamEnv<'tcx>,
|
2021-12-12 12:34:46 +08:00
|
|
|
trait_pred: ty::PolyTraitPredicate<'tcx>,
|
2018-09-07 09:34:09 -04:00
|
|
|
dep_node: DepNodeIndex,
|
|
|
|
result: EvaluationResult,
|
|
|
|
) {
|
2017-08-17 17:38:16 +03:00
|
|
|
// Avoid caching results that depend on more than just the trait-ref
|
|
|
|
// - the stack can create recursion.
|
|
|
|
if result.is_stack_dependent() {
|
2015-10-18 19:15:57 +03:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-09-15 18:17:38 -05:00
|
|
|
// Neither the global nor local cache is aware of intercrate
|
|
|
|
// mode, so don't do any caching. In particular, we might
|
|
|
|
// re-use the same `InferCtxt` with both an intercrate
|
|
|
|
// and non-intercrate `SelectionContext`
|
|
|
|
if self.intercrate {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-05-23 04:19:47 -04:00
|
|
|
if self.can_use_global_caches(param_env) {
|
2021-12-12 12:34:46 +08:00
|
|
|
if !trait_pred.needs_infer() {
|
|
|
|
debug!(?trait_pred, ?result, "insert_evaluation_cache global");
|
2018-04-01 08:14:58 +02:00
|
|
|
// This may overwrite the cache with the same value
|
|
|
|
// FIXME: Due to #50507 this overwrites the different values
|
|
|
|
// This should be changed to use HashMapExt::insert_same
|
|
|
|
// when that is fixed
|
2021-12-12 12:34:46 +08:00
|
|
|
self.tcx().evaluation_cache.insert(param_env.and(trait_pred), dep_node, result);
|
2016-04-29 06:00:23 +03:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-12 12:34:46 +08:00
|
|
|
debug!(?trait_pred, ?result, "insert_evaluation_cache");
|
|
|
|
self.infcx.evaluation_cache.insert(param_env.and(trait_pred), dep_node, result);
|
2015-10-18 19:15:57 +03:00
|
|
|
}
|
|
|
|
|
2019-11-21 18:40:27 +00:00
|
|
|
/// For various reasons, it's possible for a subobligation
|
|
|
|
/// to have a *lower* recursion_depth than the obligation used to create it.
|
|
|
|
/// Projection sub-obligations may be returned from the projection cache,
|
|
|
|
/// which results in obligations with an 'old' `recursion_depth`.
|
2020-07-24 19:10:22 +01:00
|
|
|
/// Additionally, methods like `InferCtxt.subtype_predicate` produce
|
|
|
|
/// subobligations without taking in a 'parent' depth, causing the
|
|
|
|
/// generated subobligations to have a `recursion_depth` of `0`.
|
2019-11-21 18:40:27 +00:00
|
|
|
///
|
2021-04-19 15:57:08 +03:00
|
|
|
/// To ensure that obligation_depth never decreases, we force all subobligations
|
2019-11-21 18:40:27 +00:00
|
|
|
/// to have at least the depth of the original obligation.
|
2019-12-22 17:42:04 -05:00
|
|
|
fn add_depth<T: 'cx, I: Iterator<Item = &'cx mut Obligation<'tcx, T>>>(
|
|
|
|
&self,
|
|
|
|
it: I,
|
|
|
|
min_depth: usize,
|
|
|
|
) {
|
2018-12-20 04:02:12 -05:00
|
|
|
it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1);
|
|
|
|
}
|
|
|
|
|
2021-09-01 16:34:28 +00:00
|
|
|
fn check_recursion_depth<T: Display + TypeFoldable<'tcx>>(
|
2019-01-02 21:19:03 -05:00
|
|
|
&self,
|
2021-09-01 16:34:28 +00:00
|
|
|
depth: usize,
|
|
|
|
error_obligation: &Obligation<'tcx, T>,
|
2019-12-22 17:42:04 -05:00
|
|
|
) -> Result<(), OverflowError> {
|
2021-09-01 16:34:28 +00:00
|
|
|
if !self.infcx.tcx.recursion_limit().value_within_limit(depth) {
|
2018-12-11 14:18:30 -05:00
|
|
|
match self.query_mode {
|
|
|
|
TraitQueryMode::Standard => {
|
2021-10-05 18:53:24 +01:00
|
|
|
if self.infcx.is_tainted_by_errors() {
|
|
|
|
return Err(OverflowError::ErrorReporting);
|
|
|
|
}
|
2021-09-01 16:34:28 +00:00
|
|
|
self.infcx.report_overflow_error(error_obligation, true);
|
2018-12-11 14:18:30 -05:00
|
|
|
}
|
|
|
|
TraitQueryMode::Canonical => {
|
2021-10-10 00:44:34 -04:00
|
|
|
return Err(OverflowError::Canonical);
|
2018-12-11 14:18:30 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2021-09-01 16:34:28 +00:00
|
|
|
/// Checks that the recursion limit has not been exceeded.
|
|
|
|
///
|
|
|
|
/// The weird return type of this function allows it to be used with the `try` (`?`)
|
|
|
|
/// operator within certain functions.
|
2021-09-15 09:17:35 +00:00
|
|
|
#[inline(always)]
|
2021-09-01 16:34:28 +00:00
|
|
|
fn check_recursion_limit<T: Display + TypeFoldable<'tcx>, V: Display + TypeFoldable<'tcx>>(
|
|
|
|
&self,
|
|
|
|
obligation: &Obligation<'tcx, T>,
|
|
|
|
error_obligation: &Obligation<'tcx, V>,
|
|
|
|
) -> Result<(), OverflowError> {
|
|
|
|
self.check_recursion_depth(obligation.recursion_depth, error_obligation)
|
|
|
|
}
|
|
|
|
|
2017-07-10 17:10:30 -04:00
|
|
|
fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
|
2018-09-07 09:34:09 -04:00
|
|
|
where
|
|
|
|
OP: FnOnce(&mut Self) -> R,
|
2017-07-10 17:10:30 -04:00
|
|
|
{
|
2019-12-22 17:42:04 -05:00
|
|
|
let (result, dep_node) =
|
2021-03-18 19:38:50 +01:00
|
|
|
self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self));
|
2017-07-10 17:10:30 -04:00
|
|
|
self.tcx().dep_graph.read_index(dep_node);
|
|
|
|
(result, dep_node)
|
|
|
|
}
|
|
|
|
|
2021-10-22 10:58:38 -03:00
|
|
|
/// filter_impls filters constant trait obligations and candidates that have a positive impl
|
|
|
|
/// for a negative goal and a negative impl for a positive goal
|
2021-07-24 15:48:51 +08:00
|
|
|
#[instrument(level = "debug", skip(self))]
|
2021-07-23 00:01:47 +08:00
|
|
|
fn filter_impls(
|
2021-10-20 10:54:48 -03:00
|
|
|
&mut self,
|
2021-10-22 10:56:32 -03:00
|
|
|
candidates: Vec<SelectionCandidate<'tcx>>,
|
|
|
|
obligation: &TraitObligation<'tcx>,
|
|
|
|
) -> Vec<SelectionCandidate<'tcx>> {
|
2021-10-20 10:54:48 -03:00
|
|
|
let tcx = self.tcx();
|
2021-10-22 10:56:32 -03:00
|
|
|
let mut result = Vec::with_capacity(candidates.len());
|
|
|
|
|
|
|
|
for candidate in candidates {
|
|
|
|
// Respect const trait obligations
|
2021-12-12 12:34:46 +08:00
|
|
|
if obligation.is_const() {
|
2021-10-22 10:56:32 -03:00
|
|
|
match candidate {
|
|
|
|
// const impl
|
|
|
|
ImplCandidate(def_id)
|
|
|
|
if tcx.impl_constness(def_id) == hir::Constness::Const => {}
|
|
|
|
// const param
|
2022-01-26 19:24:01 -08:00
|
|
|
ParamCandidate(trait_pred) if trait_pred.is_const_if_const() => {}
|
2021-10-22 10:56:32 -03:00
|
|
|
// auto trait impl
|
|
|
|
AutoImplCandidate(..) => {}
|
|
|
|
// generator, this will raise error in other places
|
|
|
|
// or ignore error with const_async_blocks feature
|
|
|
|
GeneratorCandidate => {}
|
|
|
|
// FnDef where the function is const
|
|
|
|
FnPointerCandidate { is_const: true } => {}
|
2022-03-21 16:52:41 +11:00
|
|
|
ConstDestructCandidate(_) => {}
|
2021-10-22 10:56:32 -03:00
|
|
|
_ => {
|
|
|
|
// reject all other types of candidates
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-20 10:54:48 -03:00
|
|
|
if let ImplCandidate(def_id) = candidate {
|
2021-10-22 10:56:32 -03:00
|
|
|
if ty::ImplPolarity::Reservation == tcx.impl_polarity(def_id)
|
|
|
|
|| obligation.polarity() == tcx.impl_polarity(def_id)
|
2021-10-20 18:05:06 -03:00
|
|
|
|| self.allow_negative_impls
|
2021-10-22 10:56:32 -03:00
|
|
|
{
|
|
|
|
result.push(candidate);
|
|
|
|
}
|
2021-10-20 10:54:48 -03:00
|
|
|
} else {
|
2021-10-22 10:56:32 -03:00
|
|
|
result.push(candidate);
|
2021-10-20 10:54:48 -03:00
|
|
|
}
|
2021-10-22 10:56:32 -03:00
|
|
|
}
|
|
|
|
|
|
|
|
result
|
2021-10-20 10:54:48 -03:00
|
|
|
}
|
|
|
|
|
|
|
|
/// filter_reservation_impls filter reservation impl for any goal as ambiguous
|
|
|
|
#[instrument(level = "debug", skip(self))]
|
|
|
|
fn filter_reservation_impls(
|
2019-07-27 22:18:34 +03:00
|
|
|
&mut self,
|
2018-09-07 09:34:09 -04:00
|
|
|
candidate: SelectionCandidate<'tcx>,
|
2021-07-23 00:01:47 +08:00
|
|
|
obligation: &TraitObligation<'tcx>,
|
2018-09-07 09:34:09 -04:00
|
|
|
) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
|
2021-07-23 00:01:47 +08:00
|
|
|
let tcx = self.tcx();
|
2021-10-20 10:54:48 -03:00
|
|
|
// Treat reservation impls as ambiguity.
|
2015-12-22 10:20:47 -08:00
|
|
|
if let ImplCandidate(def_id) = candidate {
|
2021-10-13 16:19:29 -03:00
|
|
|
if let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) {
|
|
|
|
if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes {
|
|
|
|
let attrs = tcx.get_attrs(def_id);
|
|
|
|
let attr = tcx.sess.find_by_name(&attrs, sym::rustc_reservation_impl);
|
|
|
|
let value = attr.and_then(|a| a.value_str());
|
|
|
|
if let Some(value) = value {
|
|
|
|
debug!(
|
2021-10-22 10:57:10 -03:00
|
|
|
"filter_reservation_impls: \
|
2020-01-08 22:06:25 +01:00
|
|
|
reservation impl ambiguity on {:?}",
|
2021-10-13 16:19:29 -03:00
|
|
|
def_id
|
|
|
|
);
|
|
|
|
intercrate_ambiguity_clauses.push(
|
|
|
|
IntercrateAmbiguityCause::ReservationImpl {
|
|
|
|
message: value.to_string(),
|
|
|
|
},
|
|
|
|
);
|
2019-07-27 22:18:34 +03:00
|
|
|
}
|
2019-07-14 00:09:46 +03:00
|
|
|
}
|
2021-10-13 16:19:29 -03:00
|
|
|
return Ok(None);
|
|
|
|
}
|
2015-12-22 10:20:47 -08:00
|
|
|
}
|
|
|
|
Ok(Some(candidate))
|
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
|
2017-11-23 19:05:23 +02:00
|
|
|
debug!("is_knowable(intercrate={:?})", self.intercrate);
|
2015-03-30 17:46:34 -04:00
|
|
|
|
2021-10-20 14:12:11 -03:00
|
|
|
if !self.intercrate || stack.obligation.polarity() == ty::ImplPolarity::Negative {
|
2017-11-22 23:01:51 +02:00
|
|
|
return None;
|
2015-03-30 17:46:34 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
let obligation = &stack.obligation;
|
2020-10-24 02:21:18 +02:00
|
|
|
let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
|
2015-03-30 17:46:34 -04:00
|
|
|
|
2019-02-28 22:43:53 +00:00
|
|
|
// Okay to skip binder because of the nature of the
|
2015-03-30 17:46:34 -04:00
|
|
|
// trait-ref-is-knowable check, which does not care about
|
2019-02-28 22:43:53 +00:00
|
|
|
// bound regions.
|
2017-08-28 16:50:41 -04:00
|
|
|
let trait_ref = predicate.skip_binder().trait_ref;
|
2015-03-30 17:46:34 -04:00
|
|
|
|
2020-02-08 19:14:50 +01:00
|
|
|
coherence::trait_ref_is_knowable(self.tcx(), trait_ref)
|
2015-03-30 17:46:34 -04:00
|
|
|
}
|
|
|
|
|
2019-02-08 14:53:55 +01:00
|
|
|
/// Returns `true` if the global caches can be used.
|
2017-05-23 04:19:47 -04:00
|
|
|
fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool {
|
2020-04-06 22:29:18 +02:00
|
|
|
// If there are any inference variables in the `ParamEnv`, then we
|
2019-12-02 17:44:16 +02:00
|
|
|
// always use a cache local to this particular scope. Otherwise, we
|
|
|
|
// switch to a global cache.
|
2020-04-06 22:29:18 +02:00
|
|
|
if param_env.needs_infer() {
|
2016-04-29 06:00:23 +03:00
|
|
|
return false;
|
2015-02-06 19:11:50 -05:00
|
|
|
}
|
2014-10-22 11:35:53 -04:00
|
|
|
|
2014-11-03 14:48:03 -05:00
|
|
|
// Avoid using the master cache during coherence and just rely
|
|
|
|
// on the local cache. This effectively disables caching
|
|
|
|
// during coherence. It is really just a simplification to
|
|
|
|
// avoid us having to fear that coherence results "pollute"
|
|
|
|
// the master cache. Since coherence executes pretty quickly,
|
|
|
|
// it's not worth going to more trouble to increase the
|
2019-05-17 02:20:14 +01:00
|
|
|
// hit-rate, I don't think.
|
2020-02-08 19:14:50 +01:00
|
|
|
if self.intercrate {
|
2016-04-29 06:00:23 +03:00
|
|
|
return false;
|
2014-11-03 14:48:03 -05:00
|
|
|
}
|
|
|
|
|
2014-10-22 11:35:53 -04:00
|
|
|
// Otherwise, we can use the global cache.
|
2016-04-29 06:00:23 +03:00
|
|
|
true
|
2014-09-12 10:53:35 -04:00
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
fn check_candidate_cache(
|
|
|
|
&mut self,
|
2021-12-12 12:34:46 +08:00
|
|
|
mut param_env: ty::ParamEnv<'tcx>,
|
2020-05-23 11:09:32 +02:00
|
|
|
cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
|
2018-09-07 09:34:09 -04:00
|
|
|
) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
|
2021-09-20 14:23:21 -05:00
|
|
|
// Neither the global nor local cache is aware of intercrate
|
|
|
|
// mode, so don't do any caching. In particular, we might
|
|
|
|
// re-use the same `InferCtxt` with both an intercrate
|
|
|
|
// and non-intercrate `SelectionContext`
|
|
|
|
if self.intercrate {
|
|
|
|
return None;
|
|
|
|
}
|
2017-07-10 17:10:30 -04:00
|
|
|
let tcx = self.tcx();
|
2021-12-12 12:34:46 +08:00
|
|
|
let mut pred = cache_fresh_trait_pred.skip_binder();
|
2021-12-21 13:23:59 +08:00
|
|
|
pred.remap_constness(tcx, &mut param_env);
|
2021-12-12 12:34:46 +08:00
|
|
|
|
2017-05-23 04:19:47 -04:00
|
|
|
if self.can_use_global_caches(param_env) {
|
2021-12-12 12:34:46 +08:00
|
|
|
if let Some(res) = tcx.selection_cache.get(¶m_env.and(pred), tcx) {
|
2020-08-02 15:03:47 +02:00
|
|
|
return Some(res);
|
2016-04-29 06:00:23 +03:00
|
|
|
}
|
|
|
|
}
|
2021-12-12 12:34:46 +08:00
|
|
|
self.infcx.selection_cache.get(¶m_env.and(pred), tcx)
|
2014-09-12 10:53:35 -04:00
|
|
|
}
|
|
|
|
|
2018-10-22 00:12:16 -04:00
|
|
|
/// Determines whether can we safely cache the result
|
2019-05-17 02:20:14 +01:00
|
|
|
/// of selecting an obligation. This is almost always `true`,
|
|
|
|
/// except when dealing with certain `ParamCandidate`s.
|
2018-10-22 00:12:16 -04:00
|
|
|
///
|
2019-05-17 02:20:14 +01:00
|
|
|
/// Ordinarily, a `ParamCandidate` will contain no inference variables,
|
|
|
|
/// since it was usually produced directly from a `DefId`. However,
|
2018-10-22 00:12:16 -04:00
|
|
|
/// certain cases (currently only librustdoc's blanket impl finder),
|
2019-05-17 02:20:14 +01:00
|
|
|
/// a `ParamEnv` may be explicitly constructed with inference types.
|
2018-10-22 00:12:16 -04:00
|
|
|
/// When this is the case, we do *not* want to cache the resulting selection
|
|
|
|
/// candidate. This is due to the fact that it might not always be possible
|
|
|
|
/// to equate the obligation's trait ref and the candidate's trait ref,
|
|
|
|
/// if more constraints end up getting added to an inference variable.
|
|
|
|
///
|
|
|
|
/// Because of this, we always want to re-run the full selection
|
|
|
|
/// process for our obligation the next time we see it, since
|
2019-05-17 02:20:14 +01:00
|
|
|
/// we might end up picking a different `SelectionCandidate` (or none at all).
|
2019-12-22 17:42:04 -05:00
|
|
|
fn can_cache_candidate(
|
|
|
|
&self,
|
|
|
|
result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>,
|
|
|
|
) -> bool {
|
2021-09-20 14:23:21 -05:00
|
|
|
// Neither the global nor local cache is aware of intercrate
|
|
|
|
// mode, so don't do any caching. In particular, we might
|
|
|
|
// re-use the same `InferCtxt` with both an intercrate
|
|
|
|
// and non-intercrate `SelectionContext`
|
|
|
|
if self.intercrate {
|
|
|
|
return false;
|
|
|
|
}
|
2018-10-22 00:12:16 -04:00
|
|
|
match result {
|
2020-04-06 22:29:18 +02:00
|
|
|
Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(),
|
2019-12-22 17:42:04 -05:00
|
|
|
_ => true,
|
2018-10-22 00:12:16 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
fn insert_candidate_cache(
|
|
|
|
&mut self,
|
2021-12-12 12:34:46 +08:00
|
|
|
mut param_env: ty::ParamEnv<'tcx>,
|
2018-09-07 09:34:09 -04:00
|
|
|
cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
|
|
|
|
dep_node: DepNodeIndex,
|
|
|
|
candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
|
|
|
|
) {
|
2017-07-10 17:10:30 -04:00
|
|
|
let tcx = self.tcx();
|
2021-12-12 12:34:46 +08:00
|
|
|
let mut pred = cache_fresh_trait_pred.skip_binder();
|
|
|
|
|
2021-12-21 13:23:59 +08:00
|
|
|
pred.remap_constness(tcx, &mut param_env);
|
2018-10-22 00:12:16 -04:00
|
|
|
|
|
|
|
if !self.can_cache_candidate(&candidate) {
|
2021-12-12 12:34:46 +08:00
|
|
|
debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable");
|
2018-10-22 00:12:16 -04:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-05-23 04:19:47 -04:00
|
|
|
if self.can_use_global_caches(param_env) {
|
2018-09-13 13:40:25 -04:00
|
|
|
if let Err(Overflow) = candidate {
|
2019-05-17 02:20:14 +01:00
|
|
|
// Don't cache overflow globally; we only produce this in certain modes.
|
2021-12-12 12:34:46 +08:00
|
|
|
} else if !pred.needs_infer() {
|
2020-04-06 22:29:18 +02:00
|
|
|
if !candidate.needs_infer() {
|
2021-12-12 12:34:46 +08:00
|
|
|
debug!(?pred, ?candidate, "insert_candidate_cache global");
|
2019-05-17 02:20:14 +01:00
|
|
|
// This may overwrite the cache with the same value.
|
2021-12-12 12:34:46 +08:00
|
|
|
tcx.selection_cache.insert(param_env.and(pred), dep_node, candidate);
|
2016-04-29 06:00:23 +03:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-12 12:34:46 +08:00
|
|
|
debug!(?pred, ?candidate, "insert_candidate_cache local");
|
|
|
|
self.infcx.selection_cache.insert(param_env.and(pred), dep_node, candidate);
|
2014-09-12 10:53:35 -04:00
|
|
|
}
|
|
|
|
|
2020-07-02 21:45:28 +01:00
|
|
|
/// Matches a predicate against the bounds of its self type.
|
|
|
|
///
|
|
|
|
/// Given an obligation like `<T as Foo>::Bar: Baz` where the self type is
|
|
|
|
/// a projection, look at the bounds of `T::Bar`, see if we can find a
|
2020-07-23 21:59:20 +01:00
|
|
|
/// `Baz` bound. We return indexes into the list returned by
|
|
|
|
/// `tcx.item_bounds` for any applicable bounds.
|
2016-07-22 18:56:22 +03:00
|
|
|
fn match_projection_obligation_against_definition_bounds(
|
2014-12-27 04:22:29 -05:00
|
|
|
&mut self,
|
|
|
|
obligation: &TraitObligation<'tcx>,
|
2020-07-23 21:59:20 +01:00
|
|
|
) -> smallvec::SmallVec<[usize; 2]> {
|
2020-10-24 02:21:18 +02:00
|
|
|
let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate);
|
2020-06-28 20:27:59 +01:00
|
|
|
let placeholder_trait_predicate =
|
2020-10-24 02:21:18 +02:00
|
|
|
self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate);
|
2022-02-11 07:18:06 +00:00
|
|
|
debug!(
|
|
|
|
?placeholder_trait_predicate,
|
|
|
|
"match_projection_obligation_against_definition_bounds"
|
|
|
|
);
|
2014-12-27 04:22:29 -05:00
|
|
|
|
2020-05-30 17:19:31 +01:00
|
|
|
let tcx = self.infcx.tcx;
|
2020-06-28 12:41:46 +01:00
|
|
|
let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() {
|
|
|
|
ty::Projection(ref data) => (data.item_def_id, data.substs),
|
|
|
|
ty::Opaque(def_id, substs) => (def_id, substs),
|
2014-12-27 04:22:29 -05:00
|
|
|
_ => {
|
2016-03-25 18:31:27 +01:00
|
|
|
span_bug!(
|
2014-12-27 04:22:29 -05:00
|
|
|
obligation.cause.span,
|
2016-07-22 18:56:22 +03:00
|
|
|
"match_projection_obligation_against_definition_bounds() called \
|
2018-09-12 16:57:19 +02:00
|
|
|
but self-ty is not a projection: {:?}",
|
2019-02-20 04:57:32 -05:00
|
|
|
placeholder_trait_predicate.trait_ref.self_ty()
|
2018-09-07 09:34:09 -04:00
|
|
|
);
|
2014-12-27 04:22:29 -05:00
|
|
|
}
|
|
|
|
};
|
2020-06-28 12:41:46 +01:00
|
|
|
let bounds = tcx.item_bounds(def_id).subst(tcx, substs);
|
2014-12-27 04:22:29 -05:00
|
|
|
|
2020-08-15 20:31:07 +01:00
|
|
|
// The bounds returned by `item_bounds` may contain duplicates after
|
|
|
|
// normalization, so try to deduplicate when possible to avoid
|
|
|
|
// unnecessary ambiguity.
|
|
|
|
let mut distinct_normalized_bounds = FxHashSet::default();
|
|
|
|
|
2020-07-23 21:59:20 +01:00
|
|
|
let matching_bounds = bounds
|
|
|
|
.iter()
|
|
|
|
.enumerate()
|
|
|
|
.filter_map(|(idx, bound)| {
|
2021-01-07 11:20:28 -05:00
|
|
|
let bound_predicate = bound.kind();
|
2021-07-22 21:56:07 +08:00
|
|
|
if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() {
|
2020-10-16 14:04:11 -04:00
|
|
|
let bound = bound_predicate.rebind(pred.trait_ref);
|
2020-07-23 21:59:20 +01:00
|
|
|
if self.infcx.probe(|_| {
|
2020-10-08 21:52:40 +01:00
|
|
|
match self.match_normalize_trait_ref(
|
2020-07-23 21:59:20 +01:00
|
|
|
obligation,
|
|
|
|
bound,
|
|
|
|
placeholder_trait_predicate.trait_ref,
|
2020-08-15 20:31:07 +01:00
|
|
|
) {
|
2020-09-07 10:01:45 +01:00
|
|
|
Ok(None) => true,
|
|
|
|
Ok(Some(normalized_trait))
|
|
|
|
if distinct_normalized_bounds.insert(normalized_trait) =>
|
|
|
|
{
|
|
|
|
true
|
2020-08-15 20:31:07 +01:00
|
|
|
}
|
2020-09-07 10:01:45 +01:00
|
|
|
_ => false,
|
2020-08-15 20:31:07 +01:00
|
|
|
}
|
2020-07-23 21:59:20 +01:00
|
|
|
}) {
|
|
|
|
return Some(idx);
|
|
|
|
}
|
2020-05-30 17:19:31 +01:00
|
|
|
}
|
2020-07-23 21:59:20 +01:00
|
|
|
None
|
|
|
|
})
|
|
|
|
.collect();
|
2018-09-07 09:34:09 -04:00
|
|
|
|
2022-02-11 07:18:06 +00:00
|
|
|
debug!(?matching_bounds, "match_projection_obligation_against_definition_bounds");
|
2020-07-23 21:59:20 +01:00
|
|
|
matching_bounds
|
2014-12-27 04:22:29 -05:00
|
|
|
}
|
|
|
|
|
2020-08-15 20:31:07 +01:00
|
|
|
/// Equates the trait in `obligation` with trait bound. If the two traits
|
|
|
|
/// can be equated and the normalized trait bound doesn't contain inference
|
|
|
|
/// variables or placeholders, the normalized bound is returned.
|
2020-10-08 21:52:40 +01:00
|
|
|
fn match_normalize_trait_ref(
|
2018-09-07 09:34:09 -04:00
|
|
|
&mut self,
|
|
|
|
obligation: &TraitObligation<'tcx>,
|
|
|
|
trait_bound: ty::PolyTraitRef<'tcx>,
|
2019-02-20 04:57:32 -05:00
|
|
|
placeholder_trait_ref: ty::TraitRef<'tcx>,
|
2020-08-15 20:31:07 +01:00
|
|
|
) -> Result<Option<ty::PolyTraitRef<'tcx>>, ()> {
|
2019-02-20 04:57:32 -05:00
|
|
|
debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars());
|
2020-07-24 19:10:22 +01:00
|
|
|
if placeholder_trait_ref.def_id != trait_bound.def_id() {
|
|
|
|
// Avoid unnecessary normalization
|
|
|
|
return Err(());
|
|
|
|
}
|
|
|
|
|
2020-08-15 20:31:07 +01:00
|
|
|
let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| {
|
|
|
|
project::normalize_with_depth(
|
|
|
|
self,
|
|
|
|
obligation.param_env,
|
|
|
|
obligation.cause.clone(),
|
|
|
|
obligation.recursion_depth + 1,
|
2020-10-24 02:21:18 +02:00
|
|
|
trait_bound,
|
2020-08-15 20:31:07 +01:00
|
|
|
)
|
|
|
|
});
|
2018-09-07 20:11:23 -04:00
|
|
|
self.infcx
|
2018-09-07 09:34:09 -04:00
|
|
|
.at(&obligation.cause, obligation.param_env)
|
2019-02-20 04:57:32 -05:00
|
|
|
.sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound)
|
2020-08-15 20:31:07 +01:00
|
|
|
.map(|InferOk { obligations: _, value: () }| {
|
|
|
|
// This method is called within a probe, so we can't have
|
|
|
|
// inference variables and placeholders escape.
|
|
|
|
if !trait_bound.needs_infer() && !trait_bound.has_placeholders() {
|
|
|
|
Some(trait_bound)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
2020-07-24 19:10:22 +01:00
|
|
|
})
|
2020-06-28 12:41:46 +01:00
|
|
|
.map_err(|_| ())
|
2014-12-27 04:22:29 -05:00
|
|
|
}
|
|
|
|
|
2022-02-21 10:26:25 +01:00
|
|
|
fn where_clause_may_apply<'o>(
|
2018-09-07 09:34:09 -04:00
|
|
|
&mut self,
|
|
|
|
stack: &TraitObligationStack<'o, 'tcx>,
|
|
|
|
where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
|
|
|
|
) -> Result<EvaluationResult, OverflowError> {
|
2018-10-16 05:42:18 -04:00
|
|
|
self.evaluation_probe(|this| {
|
|
|
|
match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
|
2020-07-22 22:43:18 +01:00
|
|
|
Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations),
|
2018-09-07 09:34:09 -04:00
|
|
|
Err(()) => Ok(EvaluatedToErr),
|
2015-01-08 21:41:42 -05:00
|
|
|
}
|
2018-09-07 09:34:09 -04:00
|
|
|
})
|
2015-01-08 21:41:42 -05:00
|
|
|
}
|
|
|
|
|
2022-02-12 13:30:30 -08:00
|
|
|
/// Return `Yes` if the obligation's predicate type applies to the env_predicate, and
|
|
|
|
/// `No` if it does not. Return `Ambiguous` in the case that the projection type is a GAT,
|
2022-02-10 22:45:58 -08:00
|
|
|
/// and applying this env_predicate constrains any of the obligation's GAT substitutions.
|
2022-02-12 13:30:30 -08:00
|
|
|
///
|
|
|
|
/// This behavior is a somewhat of a hack to prevent overconstraining inference variables
|
|
|
|
/// in cases like #91762.
|
2020-07-24 19:10:22 +01:00
|
|
|
pub(super) fn match_projection_projections(
|
|
|
|
&mut self,
|
|
|
|
obligation: &ProjectionTyObligation<'tcx>,
|
2021-02-12 22:07:46 +00:00
|
|
|
env_predicate: PolyProjectionPredicate<'tcx>,
|
2020-07-24 19:10:22 +01:00
|
|
|
potentially_unnormalized_candidates: bool,
|
2022-02-12 13:30:30 -08:00
|
|
|
) -> ProjectionMatchesProjection {
|
2020-07-24 19:10:22 +01:00
|
|
|
let mut nested_obligations = Vec::new();
|
2021-02-12 22:07:46 +00:00
|
|
|
let (infer_predicate, _) = self.infcx.replace_bound_vars_with_fresh_vars(
|
|
|
|
obligation.cause.span,
|
|
|
|
LateBoundRegionConversionTime::HigherRankedType,
|
|
|
|
env_predicate,
|
|
|
|
);
|
|
|
|
let infer_projection = if potentially_unnormalized_candidates {
|
2020-07-24 19:10:22 +01:00
|
|
|
ensure_sufficient_stack(|| {
|
|
|
|
project::normalize_with_depth_to(
|
|
|
|
self,
|
|
|
|
obligation.param_env,
|
|
|
|
obligation.cause.clone(),
|
|
|
|
obligation.recursion_depth + 1,
|
2021-02-12 22:07:46 +00:00
|
|
|
infer_predicate.projection_ty,
|
2020-07-24 19:10:22 +01:00
|
|
|
&mut nested_obligations,
|
|
|
|
)
|
|
|
|
})
|
|
|
|
} else {
|
2021-02-12 22:07:46 +00:00
|
|
|
infer_predicate.projection_ty
|
2020-07-24 19:10:22 +01:00
|
|
|
};
|
|
|
|
|
2022-02-10 22:45:58 -08:00
|
|
|
let is_match = self
|
|
|
|
.infcx
|
2020-07-24 19:10:22 +01:00
|
|
|
.at(&obligation.cause, obligation.param_env)
|
2021-02-12 22:07:46 +00:00
|
|
|
.sup(obligation.predicate, infer_projection)
|
2020-07-24 19:10:22 +01:00
|
|
|
.map_or(false, |InferOk { obligations, value: () }| {
|
|
|
|
self.evaluate_predicates_recursively(
|
|
|
|
TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()),
|
|
|
|
nested_obligations.into_iter().chain(obligations),
|
|
|
|
)
|
|
|
|
.map_or(false, |res| res.may_apply())
|
2022-02-10 22:45:58 -08:00
|
|
|
});
|
|
|
|
|
|
|
|
if is_match {
|
|
|
|
let generics = self.tcx().generics_of(obligation.predicate.item_def_id);
|
2022-02-12 13:30:30 -08:00
|
|
|
// FIXME(generic-associated-types): Addresses aggressive inference in #92917.
|
|
|
|
// If this type is a GAT, and of the GAT substs resolve to something new,
|
|
|
|
// that means that we must have newly inferred something about the GAT.
|
|
|
|
// We should give up in that case.
|
|
|
|
if !generics.params.is_empty()
|
|
|
|
&& obligation.predicate.substs[generics.parent_count..]
|
2022-02-10 22:45:58 -08:00
|
|
|
.iter()
|
|
|
|
.any(|&p| p.has_infer_types_or_consts() && self.infcx.shallow_resolve(p) != p)
|
2022-02-12 13:30:30 -08:00
|
|
|
{
|
|
|
|
ProjectionMatchesProjection::Ambiguous
|
|
|
|
} else {
|
|
|
|
ProjectionMatchesProjection::Yes
|
2022-02-10 22:45:58 -08:00
|
|
|
}
|
2022-02-12 13:30:30 -08:00
|
|
|
} else {
|
|
|
|
ProjectionMatchesProjection::No
|
2022-02-10 22:45:58 -08:00
|
|
|
}
|
2020-07-24 19:10:22 +01:00
|
|
|
}
|
|
|
|
|
2014-10-09 17:19:50 -04:00
|
|
|
///////////////////////////////////////////////////////////////////////////
|
|
|
|
// WINNOW
|
|
|
|
//
|
|
|
|
// Winnowing is the process of attempting to resolve ambiguity by
|
|
|
|
// probing further. During the winnowing process, we unify all
|
2018-10-02 20:09:32 -04:00
|
|
|
// type variables and then we also attempt to evaluate recursive
|
|
|
|
// bounds to see if they are satisfied.
|
2014-10-09 17:19:50 -04:00
|
|
|
|
2019-02-08 14:53:55 +01:00
|
|
|
/// Returns `true` if `victim` should be dropped in favor of
|
|
|
|
/// `other`. Generally speaking we will drop duplicate
|
2015-05-07 22:21:57 +03:00
|
|
|
/// candidates and prefer where-clause candidates.
|
|
|
|
///
|
|
|
|
/// See the comment for "SelectionCandidate" for more details.
|
2019-06-11 12:21:38 +03:00
|
|
|
fn candidate_should_be_dropped_in_favor_of(
|
2015-12-22 10:20:47 -08:00
|
|
|
&mut self,
|
2021-12-19 22:01:48 -05:00
|
|
|
sized_predicate: bool,
|
2015-12-22 10:20:47 -08:00
|
|
|
victim: &EvaluatedCandidate<'tcx>,
|
2018-09-07 09:34:09 -04:00
|
|
|
other: &EvaluatedCandidate<'tcx>,
|
2020-01-09 10:01:20 -05:00
|
|
|
needs_infer: bool,
|
2018-09-07 09:34:09 -04:00
|
|
|
) -> bool {
|
2018-09-12 16:57:19 +02:00
|
|
|
if victim.candidate == other.candidate {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2018-06-08 17:00:03 +01:00
|
|
|
// Check if a bound would previously have been removed when normalizing
|
|
|
|
// the param_env so that it can be given the lowest priority. See
|
|
|
|
// #50825 for the motivation for this.
|
2021-12-12 12:34:46 +08:00
|
|
|
let is_global = |cand: &ty::PolyTraitPredicate<'tcx>| {
|
2022-01-12 03:19:52 +00:00
|
|
|
cand.is_global() && !cand.has_late_bound_regions()
|
2021-10-28 13:23:49 +00:00
|
|
|
};
|
2018-06-08 17:00:03 +01:00
|
|
|
|
2020-10-19 15:38:11 +02:00
|
|
|
// (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`,
|
2022-03-21 16:52:41 +11:00
|
|
|
// `DiscriminantKindCandidate`, and `ConstDestructCandidate` to anything else.
|
2020-04-05 19:57:32 +02:00
|
|
|
//
|
|
|
|
// This is a fix for #53123 and prevents winnowing from accidentally extending the
|
|
|
|
// lifetime of a variable.
|
2020-07-24 19:10:22 +01:00
|
|
|
match (&other.candidate, &victim.candidate) {
|
|
|
|
(_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => {
|
|
|
|
bug!(
|
|
|
|
"default implementations shouldn't be recorded \
|
|
|
|
when there are other valid candidates"
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2020-04-05 19:57:32 +02:00
|
|
|
// (*)
|
2020-10-19 15:38:11 +02:00
|
|
|
(
|
|
|
|
BuiltinCandidate { has_nested: false }
|
|
|
|
| DiscriminantKindCandidate
|
2021-09-01 16:34:28 +00:00
|
|
|
| PointeeCandidate
|
2022-03-21 16:52:41 +11:00
|
|
|
| ConstDestructCandidate(_),
|
2020-10-19 15:38:11 +02:00
|
|
|
_,
|
|
|
|
) => true,
|
|
|
|
(
|
|
|
|
_,
|
|
|
|
BuiltinCandidate { has_nested: false }
|
|
|
|
| DiscriminantKindCandidate
|
2021-09-01 16:34:28 +00:00
|
|
|
| PointeeCandidate
|
2022-03-21 16:52:41 +11:00
|
|
|
| ConstDestructCandidate(_),
|
2020-10-19 15:38:11 +02:00
|
|
|
) => false,
|
2020-07-24 19:10:22 +01:00
|
|
|
|
2021-12-12 12:34:46 +08:00
|
|
|
(ParamCandidate(other), ParamCandidate(victim)) => {
|
|
|
|
let same_except_bound_vars = other.skip_binder().trait_ref
|
|
|
|
== victim.skip_binder().trait_ref
|
|
|
|
&& other.skip_binder().constness == victim.skip_binder().constness
|
|
|
|
&& other.skip_binder().polarity == victim.skip_binder().polarity
|
|
|
|
&& !other.skip_binder().trait_ref.has_escaping_bound_vars();
|
2021-09-11 09:40:19 +00:00
|
|
|
if same_except_bound_vars {
|
2021-04-25 15:11:49 -04:00
|
|
|
// See issue #84398. In short, we can generate multiple ParamCandidates which are
|
2021-05-06 10:19:51 -04:00
|
|
|
// the same except for unused bound vars. Just pick the one with the fewest bound vars
|
|
|
|
// or the current one if tied (they should both evaluate to the same answer). This is
|
|
|
|
// probably best characterized as a "hack", since we might prefer to just do our
|
|
|
|
// best to *not* create essentially duplicate candidates in the first place.
|
2021-12-12 12:34:46 +08:00
|
|
|
other.bound_vars().len() <= victim.bound_vars().len()
|
|
|
|
} else if other.skip_binder().trait_ref == victim.skip_binder().trait_ref
|
|
|
|
&& victim.skip_binder().constness == ty::BoundConstness::NotConst
|
|
|
|
&& other.skip_binder().polarity == victim.skip_binder().polarity
|
2021-08-27 08:09:00 +00:00
|
|
|
{
|
2020-11-22 04:04:49 +01:00
|
|
|
// Drop otherwise equivalent non-const candidates in favor of const candidates.
|
|
|
|
true
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
}
|
|
|
|
}
|
2020-07-24 19:10:22 +01:00
|
|
|
|
2021-09-15 11:28:10 +00:00
|
|
|
// Drop otherwise equivalent non-const fn pointer candidates
|
|
|
|
(FnPointerCandidate { .. }, FnPointerCandidate { is_const: false }) => true,
|
|
|
|
|
2021-12-19 22:01:48 -05:00
|
|
|
// If obligation is a sized predicate or the where-clause bound is
|
|
|
|
// global, prefer the projection or object candidate. See issue
|
|
|
|
// #50825 and #89352.
|
|
|
|
(ObjectCandidate(_) | ProjectionCandidate(_), ParamCandidate(ref cand)) => {
|
|
|
|
sized_predicate || is_global(cand)
|
|
|
|
}
|
|
|
|
(ParamCandidate(ref cand), ObjectCandidate(_) | ProjectionCandidate(_)) => {
|
|
|
|
!(sized_predicate || is_global(cand))
|
|
|
|
}
|
|
|
|
|
2020-07-24 19:10:22 +01:00
|
|
|
// Global bounds from the where clause should be ignored
|
|
|
|
// here (see issue #50825). Otherwise, we have a where
|
|
|
|
// clause so don't go around looking for impls.
|
|
|
|
// Arbitrarily give param candidates priority
|
|
|
|
// over projection and object candidates.
|
|
|
|
(
|
|
|
|
ParamCandidate(ref cand),
|
2018-09-07 09:34:09 -04:00
|
|
|
ImplCandidate(..)
|
|
|
|
| ClosureCandidate
|
|
|
|
| GeneratorCandidate
|
2021-09-15 11:28:10 +00:00
|
|
|
| FnPointerCandidate { .. }
|
2018-09-07 09:34:09 -04:00
|
|
|
| BuiltinObjectCandidate
|
|
|
|
| BuiltinUnsizeCandidate
|
2021-08-18 02:41:29 +08:00
|
|
|
| TraitUpcastingUnsizeCandidate(_)
|
2018-10-12 01:50:03 +01:00
|
|
|
| BuiltinCandidate { .. }
|
2021-12-19 22:01:48 -05:00
|
|
|
| TraitAliasCandidate(..),
|
2021-12-12 12:34:46 +08:00
|
|
|
) => !is_global(cand),
|
2020-07-24 19:10:22 +01:00
|
|
|
(
|
|
|
|
ImplCandidate(_)
|
|
|
|
| ClosureCandidate
|
|
|
|
| GeneratorCandidate
|
2021-09-15 11:28:10 +00:00
|
|
|
| FnPointerCandidate { .. }
|
2020-07-24 19:10:22 +01:00
|
|
|
| BuiltinObjectCandidate
|
|
|
|
| BuiltinUnsizeCandidate
|
2021-08-18 02:41:29 +08:00
|
|
|
| TraitUpcastingUnsizeCandidate(_)
|
2020-07-24 19:10:22 +01:00
|
|
|
| BuiltinCandidate { has_nested: true }
|
|
|
|
| TraitAliasCandidate(..),
|
|
|
|
ParamCandidate(ref cand),
|
|
|
|
) => {
|
|
|
|
// Prefer these to a global where-clause bound
|
|
|
|
// (see issue #50825).
|
2021-12-12 12:34:46 +08:00
|
|
|
is_global(cand) && other.evaluation.must_apply_modulo_regions()
|
2020-07-24 19:10:22 +01:00
|
|
|
}
|
|
|
|
|
2020-10-08 21:52:40 +01:00
|
|
|
(ProjectionCandidate(i), ProjectionCandidate(j))
|
|
|
|
| (ObjectCandidate(i), ObjectCandidate(j)) => {
|
2020-10-08 21:49:36 +01:00
|
|
|
// Arbitrarily pick the lower numbered candidate for backwards
|
2020-07-24 19:10:22 +01:00
|
|
|
// compatibility reasons. Don't let this affect inference.
|
2020-10-08 21:49:36 +01:00
|
|
|
i < j && !needs_infer
|
2020-07-24 19:10:22 +01:00
|
|
|
}
|
2020-10-08 21:52:40 +01:00
|
|
|
(ObjectCandidate(_), ProjectionCandidate(_))
|
|
|
|
| (ProjectionCandidate(_), ObjectCandidate(_)) => {
|
2020-07-24 19:10:22 +01:00
|
|
|
bug!("Have both object and projection candidate")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Arbitrarily give projection and object candidates priority.
|
|
|
|
(
|
2020-10-08 21:52:40 +01:00
|
|
|
ObjectCandidate(_) | ProjectionCandidate(_),
|
2018-09-07 09:34:09 -04:00
|
|
|
ImplCandidate(..)
|
|
|
|
| ClosureCandidate
|
|
|
|
| GeneratorCandidate
|
2021-09-15 11:28:10 +00:00
|
|
|
| FnPointerCandidate { .. }
|
2018-09-07 09:34:09 -04:00
|
|
|
| BuiltinObjectCandidate
|
|
|
|
| BuiltinUnsizeCandidate
|
2021-08-18 02:41:29 +08:00
|
|
|
| TraitUpcastingUnsizeCandidate(_)
|
2018-10-12 01:50:03 +01:00
|
|
|
| BuiltinCandidate { .. }
|
2020-07-24 19:10:22 +01:00
|
|
|
| TraitAliasCandidate(..),
|
|
|
|
) => true,
|
|
|
|
|
|
|
|
(
|
|
|
|
ImplCandidate(..)
|
|
|
|
| ClosureCandidate
|
|
|
|
| GeneratorCandidate
|
2021-09-15 11:28:10 +00:00
|
|
|
| FnPointerCandidate { .. }
|
2020-07-24 19:10:22 +01:00
|
|
|
| BuiltinObjectCandidate
|
|
|
|
| BuiltinUnsizeCandidate
|
2021-08-18 02:41:29 +08:00
|
|
|
| TraitUpcastingUnsizeCandidate(_)
|
2020-07-24 19:10:22 +01:00
|
|
|
| BuiltinCandidate { .. }
|
|
|
|
| TraitAliasCandidate(..),
|
2020-10-08 21:52:40 +01:00
|
|
|
ObjectCandidate(_) | ProjectionCandidate(_),
|
2020-07-24 19:10:22 +01:00
|
|
|
) => false,
|
|
|
|
|
|
|
|
(&ImplCandidate(other_def), &ImplCandidate(victim_def)) => {
|
2015-12-22 10:20:47 -08:00
|
|
|
// See if we can toss out `victim` based on specialization.
|
|
|
|
// This requires us to know *for sure* that the `other` impl applies
|
2019-05-17 02:20:14 +01:00
|
|
|
// i.e., `EvaluatedToOk`.
|
2021-08-18 16:27:25 +02:00
|
|
|
//
|
|
|
|
// FIXME(@lcnr): Using `modulo_regions` here seems kind of scary
|
|
|
|
// to me but is required for `std` to compile, so I didn't change it
|
|
|
|
// for now.
|
|
|
|
let tcx = self.tcx();
|
2018-09-20 13:56:11 -04:00
|
|
|
if other.evaluation.must_apply_modulo_regions() {
|
2020-07-24 19:10:22 +01:00
|
|
|
if tcx.specializes((other_def, victim_def)) {
|
|
|
|
return true;
|
2018-06-08 17:00:03 +01:00
|
|
|
}
|
2021-08-18 16:27:25 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if other.evaluation.must_apply_considering_regions() {
|
|
|
|
match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
|
2020-07-24 19:10:22 +01:00
|
|
|
Some(ty::ImplOverlapKind::Permitted { marker: true }) => {
|
|
|
|
// Subtle: If the predicate we are evaluating has inference
|
|
|
|
// variables, do *not* allow discarding candidates due to
|
|
|
|
// marker trait impls.
|
|
|
|
//
|
|
|
|
// Without this restriction, we could end up accidentally
|
|
|
|
// constrainting inference variables based on an arbitrarily
|
|
|
|
// chosen trait impl.
|
|
|
|
//
|
|
|
|
// Imagine we have the following code:
|
|
|
|
//
|
|
|
|
// ```rust
|
|
|
|
// #[marker] trait MyTrait {}
|
|
|
|
// impl MyTrait for u8 {}
|
|
|
|
// impl MyTrait for bool {}
|
|
|
|
// ```
|
|
|
|
//
|
|
|
|
// And we are evaluating the predicate `<_#0t as MyTrait>`.
|
|
|
|
//
|
|
|
|
// During selection, we will end up with one candidate for each
|
|
|
|
// impl of `MyTrait`. If we were to discard one impl in favor
|
|
|
|
// of the other, we would be left with one candidate, causing
|
|
|
|
// us to "successfully" select the predicate, unifying
|
|
|
|
// _#0t with (for example) `u8`.
|
|
|
|
//
|
|
|
|
// However, we have no reason to believe that this unification
|
|
|
|
// is correct - we've essentially just picked an arbitrary
|
|
|
|
// *possibility* for _#0t, and required that this be the *only*
|
|
|
|
// possibility.
|
|
|
|
//
|
|
|
|
// Eventually, we will either:
|
|
|
|
// 1) Unify all inference variables in the predicate through
|
|
|
|
// some other means (e.g. type-checking of a function). We will
|
|
|
|
// then be in a position to drop marker trait candidates
|
|
|
|
// without constraining inference variables (since there are
|
|
|
|
// none left to constrin)
|
|
|
|
// 2) Be left with some unconstrained inference variables. We
|
|
|
|
// will then correctly report an inference error, since the
|
|
|
|
// existence of multiple marker trait impls tells us nothing
|
|
|
|
// about which one should actually apply.
|
|
|
|
!needs_infer
|
|
|
|
}
|
|
|
|
Some(_) => true,
|
|
|
|
None => false,
|
2021-08-18 16:27:25 +02:00
|
|
|
}
|
2020-07-24 19:10:22 +01:00
|
|
|
} else {
|
|
|
|
false
|
2018-06-08 17:00:03 +01:00
|
|
|
}
|
|
|
|
}
|
2020-07-24 19:10:22 +01:00
|
|
|
|
|
|
|
// Everything else is ambiguous
|
|
|
|
(
|
|
|
|
ImplCandidate(_)
|
|
|
|
| ClosureCandidate
|
|
|
|
| GeneratorCandidate
|
2021-09-15 11:28:10 +00:00
|
|
|
| FnPointerCandidate { .. }
|
2020-07-24 19:10:22 +01:00
|
|
|
| BuiltinObjectCandidate
|
|
|
|
| BuiltinUnsizeCandidate
|
2021-08-18 02:41:29 +08:00
|
|
|
| TraitUpcastingUnsizeCandidate(_)
|
2020-07-24 19:10:22 +01:00
|
|
|
| BuiltinCandidate { has_nested: true }
|
|
|
|
| TraitAliasCandidate(..),
|
|
|
|
ImplCandidate(_)
|
|
|
|
| ClosureCandidate
|
|
|
|
| GeneratorCandidate
|
2021-09-15 11:28:10 +00:00
|
|
|
| FnPointerCandidate { .. }
|
2020-07-24 19:10:22 +01:00
|
|
|
| BuiltinObjectCandidate
|
|
|
|
| BuiltinUnsizeCandidate
|
2021-08-18 02:41:29 +08:00
|
|
|
| TraitUpcastingUnsizeCandidate(_)
|
2020-07-24 19:10:22 +01:00
|
|
|
| BuiltinCandidate { has_nested: true }
|
|
|
|
| TraitAliasCandidate(..),
|
|
|
|
) => false,
|
2014-09-12 10:53:35 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
fn sized_conditions(
|
|
|
|
&mut self,
|
|
|
|
obligation: &TraitObligation<'tcx>,
|
|
|
|
) -> BuiltinImplConditions<'tcx> {
|
2018-05-06 22:48:56 +01:00
|
|
|
use self::BuiltinImplConditions::{Ambiguous, None, Where};
|
2016-04-14 15:49:39 +03:00
|
|
|
|
2016-04-18 00:04:21 +03:00
|
|
|
// NOTE: binder moved to (*)
|
2019-12-22 17:42:04 -05:00
|
|
|
let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
|
2016-04-14 15:49:39 +03:00
|
|
|
|
2020-08-03 00:49:11 +02:00
|
|
|
match self_ty.kind() {
|
2020-04-16 17:38:52 -07:00
|
|
|
ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
|
2018-09-07 09:34:09 -04:00
|
|
|
| ty::Uint(_)
|
|
|
|
| ty::Int(_)
|
|
|
|
| ty::Bool
|
|
|
|
| ty::Float(_)
|
|
|
|
| ty::FnDef(..)
|
|
|
|
| ty::FnPtr(_)
|
|
|
|
| ty::RawPtr(..)
|
|
|
|
| ty::Char
|
|
|
|
| ty::Ref(..)
|
|
|
|
| ty::Generator(..)
|
|
|
|
| ty::GeneratorWitness(..)
|
|
|
|
| ty::Array(..)
|
|
|
|
| ty::Closure(..)
|
|
|
|
| ty::Never
|
2020-05-05 23:02:09 -05:00
|
|
|
| ty::Error(_) => {
|
2014-09-18 11:08:04 -04:00
|
|
|
// safe for everything
|
2018-04-24 21:45:49 -05:00
|
|
|
Where(ty::Binder::dummy(Vec::new()))
|
2014-09-18 11:08:04 -04:00
|
|
|
}
|
|
|
|
|
2018-08-22 01:35:55 +01:00
|
|
|
ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
|
2014-09-18 11:08:04 -04:00
|
|
|
|
2020-10-07 20:02:06 -04:00
|
|
|
ty::Tuple(tys) => Where(
|
2022-02-07 16:06:31 +01:00
|
|
|
obligation.predicate.rebind(tys.last().map_or_else(Vec::new, |&last| vec![last])),
|
2020-10-07 20:02:06 -04:00
|
|
|
),
|
2016-04-22 01:46:23 +03:00
|
|
|
|
2018-08-22 01:35:02 +01:00
|
|
|
ty::Adt(def, substs) => {
|
2016-04-18 00:04:21 +03:00
|
|
|
let sized_crit = def.sized_constraint(self.tcx());
|
|
|
|
// (*) binder moved here
|
2020-10-16 14:04:11 -04:00
|
|
|
Where(
|
|
|
|
obligation.predicate.rebind({
|
|
|
|
sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
|
|
|
|
}),
|
|
|
|
)
|
2014-09-18 11:08:04 -04:00
|
|
|
}
|
|
|
|
|
2018-08-23 13:51:32 -06:00
|
|
|
ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
|
2018-08-22 01:35:02 +01:00
|
|
|
ty::Infer(ty::TyVar(_)) => Ambiguous,
|
2014-11-16 18:20:19 +00:00
|
|
|
|
2020-05-12 01:56:29 -04:00
|
|
|
ty::Placeholder(..)
|
2018-11-03 15:15:33 +01:00
|
|
|
| ty::Bound(..)
|
2020-04-16 17:38:52 -07:00
|
|
|
| ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
|
2019-12-22 17:42:04 -05:00
|
|
|
bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
|
2014-09-18 11:08:04 -04:00
|
|
|
}
|
2016-04-18 00:04:21 +03:00
|
|
|
}
|
|
|
|
}
|
2014-09-18 11:08:04 -04:00
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
fn copy_clone_conditions(
|
|
|
|
&mut self,
|
|
|
|
obligation: &TraitObligation<'tcx>,
|
|
|
|
) -> BuiltinImplConditions<'tcx> {
|
2016-04-18 00:04:21 +03:00
|
|
|
// NOTE: binder moved to (*)
|
2019-12-22 17:42:04 -05:00
|
|
|
let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty());
|
2014-09-18 11:08:04 -04:00
|
|
|
|
2018-05-06 22:48:56 +01:00
|
|
|
use self::BuiltinImplConditions::{Ambiguous, None, Where};
|
2014-09-18 11:08:04 -04:00
|
|
|
|
2020-10-16 15:14:38 -04:00
|
|
|
match *self_ty.kind() {
|
2018-09-07 09:34:09 -04:00
|
|
|
ty::Infer(ty::IntVar(_))
|
|
|
|
| ty::Infer(ty::FloatVar(_))
|
|
|
|
| ty::FnDef(..)
|
|
|
|
| ty::FnPtr(_)
|
2020-05-05 23:02:09 -05:00
|
|
|
| ty::Error(_) => Where(ty::Binder::dummy(Vec::new())),
|
2018-09-07 09:34:09 -04:00
|
|
|
|
|
|
|
ty::Uint(_)
|
|
|
|
| ty::Int(_)
|
|
|
|
| ty::Bool
|
|
|
|
| ty::Float(_)
|
|
|
|
| ty::Char
|
|
|
|
| ty::RawPtr(..)
|
|
|
|
| ty::Never
|
2021-06-05 17:17:35 -04:00
|
|
|
| ty::Ref(_, _, hir::Mutability::Not)
|
|
|
|
| ty::Array(..) => {
|
Move some implementations of Clone and Copy to libcore
Add implementations of `Clone` and `Copy` for some primitive types to
libcore so that they show up in the documentation. The concerned types
are the following:
* All primitive signed and unsigned integer types (`usize`, `u8`, `u16`,
`u32`, `u64`, `u128`, `isize`, `i8`, `i16`, `i32`, `i64`, `i128`);
* All primitive floating point types (`f32`, `f64`)
* `bool`
* `char`
* `!`
* Raw pointers (`*const T` and `*mut T`)
* Shared references (`&'a T`)
These types already implemented `Clone` and `Copy`, but the
implementation was provided by the compiler. The compiler no longer
provides these implementations and instead tries to look them up as
normal trait implementations. The goal of this change is to make the
implementations appear in the generated documentation.
For `Copy` specifically, the compiler would reject an attempt to write
an `impl` for the primitive types listed above with error `E0206`; this
error no longer occurs for these types, but it will still occur for the
other types that used to raise that error.
The trait implementations are guarded with `#[cfg(not(stage0))]` because
they are invalid according to the stage0 compiler. When the stage0
compiler is updated to a revision that includes this change, the
attribute will have to be removed, otherwise the stage0 build will fail
because the types mentioned above no longer implement `Clone` or `Copy`.
For type variants that are variadic, such as tuples and function
pointers, and for array types, the `Clone` and `Copy` implementations
are still provided by the compiler, because the language is not
expressive enough yet to be able to write the appropriate
implementations in Rust.
The initial plan was to add `impl` blocks guarded by `#[cfg(dox)]` to
make them apply only when generating documentation, without having to
touch the compiler. However, rustdoc's usage of the compiler still
rejected those `impl` blocks.
This is a [breaking-change] for users of `#![no_core]`, because they
will now have to supply their own implementations of `Clone` and `Copy`
for the primitive types listed above. The easiest way to do that is to
simply copy the implementations from `src/libcore/clone.rs` and
`src/libcore/marker.rs`.
Fixes #25893
2018-02-12 01:17:32 -05:00
|
|
|
// Implementations provided in libcore
|
|
|
|
None
|
2014-09-18 11:08:04 -04:00
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
ty::Dynamic(..)
|
|
|
|
| ty::Str
|
|
|
|
| ty::Slice(..)
|
|
|
|
| ty::Generator(..)
|
|
|
|
| ty::GeneratorWitness(..)
|
|
|
|
| ty::Foreign(..)
|
2019-12-16 17:28:40 +01:00
|
|
|
| ty::Ref(_, _, hir::Mutability::Mut) => None,
|
2014-09-18 11:08:04 -04:00
|
|
|
|
2018-08-22 01:35:02 +01:00
|
|
|
ty::Tuple(tys) => {
|
2016-04-18 00:04:21 +03:00
|
|
|
// (*) binder moved here
|
2022-02-07 16:06:31 +01:00
|
|
|
Where(obligation.predicate.rebind(tys.iter().collect()))
|
2014-09-18 11:08:04 -04:00
|
|
|
}
|
|
|
|
|
2020-03-13 03:23:38 +02:00
|
|
|
ty::Closure(_, substs) => {
|
2019-04-21 15:19:53 -07:00
|
|
|
// (*) binder moved here
|
2020-07-19 17:26:51 -04:00
|
|
|
let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
|
|
|
|
if let ty::Infer(ty::TyVar(_)) = ty.kind() {
|
|
|
|
// Not yet resolved.
|
|
|
|
Ambiguous
|
|
|
|
} else {
|
2020-10-16 14:04:11 -04:00
|
|
|
Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect()))
|
2020-07-19 17:26:51 -04:00
|
|
|
}
|
2017-09-13 22:40:48 +02:00
|
|
|
}
|
|
|
|
|
2018-08-23 13:51:32 -06:00
|
|
|
ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => {
|
2016-04-18 00:04:21 +03:00
|
|
|
// Fallback to whatever user-defined impls exist in this case.
|
|
|
|
None
|
2014-09-18 11:08:04 -04:00
|
|
|
}
|
|
|
|
|
2018-08-22 01:35:02 +01:00
|
|
|
ty::Infer(ty::TyVar(_)) => {
|
2014-10-09 17:19:50 -04:00
|
|
|
// Unbound type variable. Might or might not have
|
|
|
|
// applicable impls and so forth, depending on what
|
|
|
|
// those type variables wind up being bound to.
|
2016-04-18 00:04:21 +03:00
|
|
|
Ambiguous
|
2014-09-18 11:08:04 -04:00
|
|
|
}
|
|
|
|
|
2020-05-12 01:56:29 -04:00
|
|
|
ty::Placeholder(..)
|
2018-11-03 15:15:33 +01:00
|
|
|
| ty::Bound(..)
|
2020-04-16 17:38:52 -07:00
|
|
|
| ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
|
2019-12-22 17:42:04 -05:00
|
|
|
bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty);
|
2014-09-18 11:08:04 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-02-20 05:16:59 -05:00
|
|
|
/// For default impls, we need to break apart a type into its
|
|
|
|
/// "constituent types" -- meaning, the types that it contains.
|
|
|
|
///
|
|
|
|
/// Here are some (simple) examples:
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// (i32, u32) -> [i32, u32]
|
|
|
|
/// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32]
|
|
|
|
/// Bar<i32> where struct Bar<T> { x: T, y: u32 } -> [i32, u32]
|
|
|
|
/// Zed<i32> where enum Zed { A(T), B(u32) } -> [i32, u32]
|
|
|
|
/// ```
|
2020-10-05 16:51:33 -04:00
|
|
|
fn constituent_types_for_ty(
|
|
|
|
&self,
|
|
|
|
t: ty::Binder<'tcx, Ty<'tcx>>,
|
|
|
|
) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> {
|
2020-12-16 22:36:14 -05:00
|
|
|
match *t.skip_binder().kind() {
|
2018-09-07 09:34:09 -04:00
|
|
|
ty::Uint(_)
|
|
|
|
| ty::Int(_)
|
|
|
|
| ty::Bool
|
|
|
|
| ty::Float(_)
|
|
|
|
| ty::FnDef(..)
|
|
|
|
| ty::FnPtr(_)
|
|
|
|
| ty::Str
|
2020-05-05 23:02:09 -05:00
|
|
|
| ty::Error(_)
|
2020-04-16 17:38:52 -07:00
|
|
|
| ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
|
2018-09-07 09:34:09 -04:00
|
|
|
| ty::Never
|
2020-12-16 22:36:14 -05:00
|
|
|
| ty::Char => ty::Binder::dummy(Vec::new()),
|
2018-09-07 09:34:09 -04:00
|
|
|
|
2020-05-12 01:56:29 -04:00
|
|
|
ty::Placeholder(..)
|
2018-09-07 09:34:09 -04:00
|
|
|
| ty::Dynamic(..)
|
|
|
|
| ty::Param(..)
|
|
|
|
| ty::Foreign(..)
|
|
|
|
| ty::Projection(..)
|
2018-11-03 15:15:33 +01:00
|
|
|
| ty::Bound(..)
|
2020-04-16 17:38:52 -07:00
|
|
|
| ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
|
2019-12-22 17:42:04 -05:00
|
|
|
bug!("asked to assemble constituent types of unexpected type: {:?}", t);
|
2018-09-07 09:34:09 -04:00
|
|
|
}
|
2014-09-18 11:08:04 -04:00
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
|
2020-12-16 22:36:14 -05:00
|
|
|
t.rebind(vec![element_ty])
|
2015-02-02 12:14:01 +01:00
|
|
|
}
|
|
|
|
|
2020-12-16 22:36:14 -05:00
|
|
|
ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]),
|
2018-09-07 09:34:09 -04:00
|
|
|
|
2018-08-22 01:35:02 +01:00
|
|
|
ty::Tuple(ref tys) => {
|
2015-02-02 12:14:01 +01:00
|
|
|
// (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
|
2022-02-07 16:06:31 +01:00
|
|
|
t.rebind(tys.iter().collect())
|
2015-02-02 12:14:01 +01:00
|
|
|
}
|
|
|
|
|
2020-07-19 17:26:51 -04:00
|
|
|
ty::Closure(_, ref substs) => {
|
|
|
|
let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty());
|
2020-12-16 22:36:14 -05:00
|
|
|
t.rebind(vec![ty])
|
2020-07-19 17:26:51 -04:00
|
|
|
}
|
2014-09-18 11:08:04 -04:00
|
|
|
|
2020-03-13 03:23:38 +02:00
|
|
|
ty::Generator(_, ref substs, _) => {
|
2020-10-01 21:06:16 -04:00
|
|
|
let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty());
|
2020-03-13 03:23:38 +02:00
|
|
|
let witness = substs.as_generator().witness();
|
2021-12-17 18:36:18 +11:00
|
|
|
t.rebind([ty].into_iter().chain(iter::once(witness)).collect())
|
2017-10-07 16:36:28 +02:00
|
|
|
}
|
|
|
|
|
2018-08-22 01:35:02 +01:00
|
|
|
ty::GeneratorWitness(types) => {
|
2020-12-16 22:36:14 -05:00
|
|
|
debug_assert!(!types.has_escaping_bound_vars());
|
|
|
|
types.map_bound(|types| types.to_vec())
|
2016-12-26 14:34:03 +01:00
|
|
|
}
|
|
|
|
|
2019-05-17 02:20:14 +01:00
|
|
|
// For `PhantomData<T>`, we pass `T`.
|
2020-12-16 22:36:14 -05:00
|
|
|
ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()),
|
2015-03-05 16:20:02 -05:00
|
|
|
|
2020-12-16 22:36:14 -05:00
|
|
|
ty::Adt(def, substs) => {
|
|
|
|
t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect())
|
|
|
|
}
|
2017-02-14 11:32:00 +02:00
|
|
|
|
2018-08-23 13:51:32 -06:00
|
|
|
ty::Opaque(def_id, substs) => {
|
2017-02-14 11:32:00 +02:00
|
|
|
// We can resolve the `impl Trait` to its concrete type,
|
|
|
|
// which enforces a DAG between the functions requiring
|
|
|
|
// the auto trait bounds in question.
|
2020-12-16 22:36:14 -05:00
|
|
|
t.rebind(vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)])
|
2017-02-14 11:32:00 +02:00
|
|
|
}
|
2014-09-18 11:08:04 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
fn collect_predicates_for_types(
|
|
|
|
&mut self,
|
|
|
|
param_env: ty::ParamEnv<'tcx>,
|
|
|
|
cause: ObligationCause<'tcx>,
|
|
|
|
recursion_depth: usize,
|
|
|
|
trait_def_id: DefId,
|
2020-10-05 16:51:33 -04:00
|
|
|
types: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
|
2018-09-07 09:34:09 -04:00
|
|
|
) -> Vec<PredicateObligation<'tcx>> {
|
2015-03-26 15:53:00 -04:00
|
|
|
// Because the types were potentially derived from
|
|
|
|
// higher-ranked obligations they may reference late-bound
|
2020-06-06 11:52:02 +02:00
|
|
|
// regions. For example, `for<'a> Foo<&'a i32> : Copy` would
|
|
|
|
// yield a type like `for<'a> &'a i32`. In general, we
|
2015-03-26 15:53:00 -04:00
|
|
|
// maintain the invariant that we never manipulate bound
|
|
|
|
// regions, so we have to process these bound regions somehow.
|
|
|
|
//
|
|
|
|
// The strategy is to:
|
|
|
|
//
|
2018-09-07 09:46:53 -04:00
|
|
|
// 1. Instantiate those regions to placeholder regions (e.g.,
|
2020-06-06 12:05:37 +02:00
|
|
|
// `for<'a> &'a i32` becomes `&0 i32`.
|
2020-06-06 11:52:02 +02:00
|
|
|
// 2. Produce something like `&'0 i32 : Copy`
|
|
|
|
// 3. Re-bind the regions back to `for<'a> &'a i32 : Copy`
|
2015-03-26 15:53:00 -04:00
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
types
|
2020-12-16 22:36:14 -05:00
|
|
|
.as_ref()
|
2020-06-06 11:52:02 +02:00
|
|
|
.skip_binder() // binder moved -\
|
2020-02-29 03:05:14 +01:00
|
|
|
.iter()
|
2018-09-07 09:34:09 -04:00
|
|
|
.flat_map(|ty| {
|
Overhaul `TyS` and `Ty`.
Specifically, change `Ty` from this:
```
pub type Ty<'tcx> = &'tcx TyS<'tcx>;
```
to this
```
pub struct Ty<'tcx>(Interned<'tcx, TyS<'tcx>>);
```
There are two benefits to this.
- It's now a first class type, so we can define methods on it. This
means we can move a lot of methods away from `TyS`, leaving `TyS` as a
barely-used type, which is appropriate given that it's not meant to
be used directly.
- The uniqueness requirement is now explicit, via the `Interned` type.
E.g. the pointer-based `Eq` and `Hash` comes from `Interned`, rather
than via `TyS`, which wasn't obvious at all.
Much of this commit is boring churn. The interesting changes are in
these files:
- compiler/rustc_middle/src/arena.rs
- compiler/rustc_middle/src/mir/visit.rs
- compiler/rustc_middle/src/ty/context.rs
- compiler/rustc_middle/src/ty/mod.rs
Specifically:
- Most mentions of `TyS` are removed. It's very much a dumb struct now;
`Ty` has all the smarts.
- `TyS` now has `crate` visibility instead of `pub`.
- `TyS::make_for_test` is removed in favour of the static `BOOL_TY`,
which just works better with the new structure.
- The `Eq`/`Ord`/`Hash` impls are removed from `TyS`. `Interned`s impls
of `Eq`/`Hash` now suffice. `Ord` is now partly on `Interned`
(pointer-based, for the `Equal` case) and partly on `TyS`
(contents-based, for the other cases).
- There are many tedious sigil adjustments, i.e. adding or removing `*`
or `&`. They seem to be unavoidable.
2022-01-25 14:13:38 +11:00
|
|
|
let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(*ty); // <----/
|
2018-09-07 09:34:09 -04:00
|
|
|
|
2019-09-30 14:42:11 +10:00
|
|
|
self.infcx.commit_unconditionally(|_| {
|
2020-10-24 02:21:18 +02:00
|
|
|
let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty);
|
2019-12-22 17:42:04 -05:00
|
|
|
let Normalized { value: normalized_ty, mut obligations } =
|
2018-11-02 16:14:24 +01:00
|
|
|
ensure_sufficient_stack(|| {
|
|
|
|
project::normalize_with_depth(
|
|
|
|
self,
|
|
|
|
param_env,
|
|
|
|
cause.clone(),
|
|
|
|
recursion_depth,
|
2020-10-24 02:21:18 +02:00
|
|
|
placeholder_ty,
|
2018-11-02 16:14:24 +01:00
|
|
|
)
|
|
|
|
});
|
2020-06-06 11:52:02 +02:00
|
|
|
let placeholder_obligation = predicate_for_trait_def(
|
2020-01-05 20:27:00 +01:00
|
|
|
self.tcx(),
|
2018-09-07 09:34:09 -04:00
|
|
|
param_env,
|
|
|
|
cause.clone(),
|
|
|
|
trait_def_id,
|
|
|
|
recursion_depth,
|
|
|
|
normalized_ty,
|
|
|
|
&[],
|
|
|
|
);
|
2020-06-06 11:52:02 +02:00
|
|
|
obligations.push(placeholder_obligation);
|
2018-09-07 20:11:23 -04:00
|
|
|
obligations
|
2018-09-07 09:34:09 -04:00
|
|
|
})
|
2015-02-27 01:13:31 +01:00
|
|
|
})
|
2018-09-07 09:34:09 -04:00
|
|
|
.collect()
|
2015-02-27 01:13:31 +01:00
|
|
|
}
|
|
|
|
|
2014-09-12 10:53:35 -04:00
|
|
|
///////////////////////////////////////////////////////////////////////////
|
|
|
|
// Matching
|
|
|
|
//
|
|
|
|
// Matching is a common path used for both evaluation and
|
|
|
|
// confirmation. It basically unifies types that appear in impls
|
|
|
|
// and traits. This does affect the surrounding environment;
|
|
|
|
// therefore, when used during evaluation, match routines must be
|
|
|
|
// run inside of a `probe()` so that their side-effects are
|
|
|
|
// contained.
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
fn rematch_impl(
|
|
|
|
&mut self,
|
|
|
|
impl_def_id: DefId,
|
|
|
|
obligation: &TraitObligation<'tcx>,
|
2019-02-09 22:11:53 +08:00
|
|
|
) -> Normalized<'tcx, SubstsRef<'tcx>> {
|
2020-05-22 17:48:07 +00:00
|
|
|
match self.match_impl(impl_def_id, obligation) {
|
2018-09-07 20:11:23 -04:00
|
|
|
Ok(substs) => substs,
|
2014-10-09 17:19:50 -04:00
|
|
|
Err(()) => {
|
2022-02-11 07:18:06 +00:00
|
|
|
bug!(
|
|
|
|
"Impl {:?} was matchable against {:?} but now is not",
|
|
|
|
impl_def_id,
|
|
|
|
obligation
|
2018-09-07 09:34:09 -04:00
|
|
|
);
|
2014-10-09 17:19:50 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-16 16:23:42 -04:00
|
|
|
#[tracing::instrument(level = "debug", skip(self))]
|
2018-09-07 09:34:09 -04:00
|
|
|
fn match_impl(
|
|
|
|
&mut self,
|
|
|
|
impl_def_id: DefId,
|
|
|
|
obligation: &TraitObligation<'tcx>,
|
2019-02-09 22:11:53 +08:00
|
|
|
) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> {
|
2015-06-25 23:42:17 +03:00
|
|
|
let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
|
2014-11-16 07:10:37 -05:00
|
|
|
|
|
|
|
// Before we create the substitutions and everything, first
|
|
|
|
// consider a "quick reject". This avoids creating more types
|
|
|
|
// and so forth that we need to.
|
2015-04-21 18:59:58 +03:00
|
|
|
if self.fast_reject_trait_refs(obligation, &impl_trait_ref) {
|
2014-11-16 07:10:37 -05:00
|
|
|
return Err(());
|
|
|
|
}
|
|
|
|
|
2020-06-28 20:27:59 +01:00
|
|
|
let placeholder_obligation =
|
2020-10-24 02:21:18 +02:00
|
|
|
self.infcx().replace_bound_vars_with_placeholders(obligation.predicate);
|
2020-06-06 11:52:02 +02:00
|
|
|
let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref;
|
2015-04-19 23:38:37 +03:00
|
|
|
|
2019-12-22 17:42:04 -05:00
|
|
|
let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id);
|
2018-09-07 09:34:09 -04:00
|
|
|
|
|
|
|
let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
|
|
|
|
|
2021-07-16 16:23:42 -04:00
|
|
|
debug!(?impl_trait_ref);
|
|
|
|
|
2019-12-22 17:42:04 -05:00
|
|
|
let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
|
2018-11-02 16:14:24 +01:00
|
|
|
ensure_sufficient_stack(|| {
|
|
|
|
project::normalize_with_depth(
|
|
|
|
self,
|
|
|
|
obligation.param_env,
|
|
|
|
obligation.cause.clone(),
|
|
|
|
obligation.recursion_depth + 1,
|
2020-10-24 02:21:18 +02:00
|
|
|
impl_trait_ref,
|
2018-11-02 16:14:24 +01:00
|
|
|
)
|
|
|
|
});
|
2018-09-07 09:34:09 -04:00
|
|
|
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref);
|
2018-09-07 09:34:09 -04:00
|
|
|
|
2021-07-15 10:03:39 -04:00
|
|
|
let cause = ObligationCause::new(
|
|
|
|
obligation.cause.span,
|
|
|
|
obligation.cause.body_id,
|
2021-09-15 22:58:40 -04:00
|
|
|
ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id),
|
2021-07-15 10:03:39 -04:00
|
|
|
);
|
|
|
|
|
2019-12-22 17:42:04 -05:00
|
|
|
let InferOk { obligations, .. } = self
|
|
|
|
.infcx
|
2021-07-15 10:03:39 -04:00
|
|
|
.at(&cause, obligation.param_env)
|
2020-06-06 11:52:02 +02:00
|
|
|
.eq(placeholder_obligation_trait_ref, impl_trait_ref)
|
2018-09-07 09:34:09 -04:00
|
|
|
.map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
|
2018-03-03 18:47:17 -06:00
|
|
|
nested_obligations.extend(obligations);
|
2014-12-14 07:17:23 -05:00
|
|
|
|
2020-02-08 19:14:50 +01:00
|
|
|
if !self.intercrate
|
2019-07-14 00:09:46 +03:00
|
|
|
&& self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation
|
2019-07-13 18:02:00 +03:00
|
|
|
{
|
|
|
|
debug!("match_impl: reservation impls only apply in intercrate mode");
|
|
|
|
return Err(());
|
|
|
|
}
|
|
|
|
|
2021-07-16 16:23:42 -04:00
|
|
|
debug!(?impl_substs, ?nested_obligations, "match_impl: success");
|
2019-12-22 17:42:04 -05:00
|
|
|
Ok(Normalized { value: impl_substs, obligations: nested_obligations })
|
2014-10-09 17:19:50 -04:00
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
fn fast_reject_trait_refs(
|
|
|
|
&mut self,
|
2022-02-21 13:44:55 +01:00
|
|
|
obligation: &TraitObligation<'tcx>,
|
|
|
|
impl_trait_ref: &ty::TraitRef<'tcx>,
|
2018-09-07 09:34:09 -04:00
|
|
|
) -> bool {
|
2014-11-16 07:10:37 -05:00
|
|
|
// We can avoid creating type variables and doing the full
|
|
|
|
// substitution if we find that any of the input types, when
|
|
|
|
// simplified, do not match.
|
|
|
|
|
2021-03-08 15:32:41 -08:00
|
|
|
iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs).any(
|
2020-03-23 06:04:03 +02:00
|
|
|
|(obligation_arg, impl_arg)| {
|
|
|
|
match (obligation_arg.unpack(), impl_arg.unpack()) {
|
|
|
|
(GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => {
|
2021-05-07 20:00:02 +02:00
|
|
|
// Note, we simplify parameters for the obligation but not the
|
|
|
|
// impl so that we do not reject a blanket impl but do reject
|
|
|
|
// more concrete impls if we're searching for `T: Trait`.
|
|
|
|
let simplified_obligation_ty = fast_reject::simplify_type(
|
|
|
|
self.tcx(),
|
|
|
|
obligation_ty,
|
2022-02-21 13:44:55 +01:00
|
|
|
TreatParams::AsBoundTypes,
|
|
|
|
);
|
|
|
|
let simplified_impl_ty = fast_reject::simplify_type(
|
|
|
|
self.tcx(),
|
|
|
|
impl_ty,
|
|
|
|
TreatParams::AsPlaceholders,
|
2021-05-07 20:00:02 +02:00
|
|
|
);
|
2020-03-23 06:04:03 +02:00
|
|
|
|
|
|
|
simplified_obligation_ty.is_some()
|
|
|
|
&& simplified_impl_ty.is_some()
|
|
|
|
&& simplified_obligation_ty != simplified_impl_ty
|
|
|
|
}
|
|
|
|
(GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => {
|
|
|
|
// Lifetimes can never cause a rejection.
|
|
|
|
false
|
|
|
|
}
|
|
|
|
(GenericArgKind::Const(_), GenericArgKind::Const(_)) => {
|
|
|
|
// Conservatively ignore consts (i.e. assume they might
|
|
|
|
// unify later) until we have `fast_reject` support for
|
|
|
|
// them (if we'll ever need it, even).
|
|
|
|
false
|
|
|
|
}
|
|
|
|
_ => unreachable!(),
|
|
|
|
}
|
2019-12-22 17:42:04 -05:00
|
|
|
},
|
|
|
|
)
|
2014-11-16 07:10:37 -05:00
|
|
|
}
|
|
|
|
|
2015-01-08 21:41:42 -05:00
|
|
|
/// Normalize `where_clause_trait_ref` and try to match it against
|
2019-02-08 14:53:55 +01:00
|
|
|
/// `obligation`. If successful, return any predicates that
|
2020-10-08 21:52:40 +01:00
|
|
|
/// result from the normalization.
|
2018-09-07 09:34:09 -04:00
|
|
|
fn match_where_clause_trait_ref(
|
|
|
|
&mut self,
|
|
|
|
obligation: &TraitObligation<'tcx>,
|
|
|
|
where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
|
|
|
|
) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
|
2018-03-03 18:47:17 -06:00
|
|
|
self.match_poly_trait_ref(obligation, where_clause_trait_ref)
|
2015-01-08 21:41:42 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns `Ok` if `poly_trait_ref` being true implies that the
|
|
|
|
/// obligation is satisfied.
|
2021-08-20 13:36:04 +00:00
|
|
|
#[instrument(skip(self), level = "debug")]
|
2018-09-07 09:34:09 -04:00
|
|
|
fn match_poly_trait_ref(
|
|
|
|
&mut self,
|
|
|
|
obligation: &TraitObligation<'tcx>,
|
|
|
|
poly_trait_ref: ty::PolyTraitRef<'tcx>,
|
|
|
|
) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
|
|
|
|
self.infcx
|
|
|
|
.at(&obligation.cause, obligation.param_env)
|
|
|
|
.sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
|
|
|
|
.map(|InferOk { obligations, .. }| obligations)
|
|
|
|
.map_err(|_| ())
|
2014-10-09 17:19:50 -04:00
|
|
|
}
|
|
|
|
|
2014-09-12 10:53:35 -04:00
|
|
|
///////////////////////////////////////////////////////////////////////////
|
|
|
|
// Miscellany
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
fn match_fresh_trait_refs(
|
|
|
|
&self,
|
2021-12-12 12:34:46 +08:00
|
|
|
previous: ty::PolyTraitPredicate<'tcx>,
|
|
|
|
current: ty::PolyTraitPredicate<'tcx>,
|
2019-03-26 00:13:09 +01:00
|
|
|
param_env: ty::ParamEnv<'tcx>,
|
2018-09-07 09:34:09 -04:00
|
|
|
) -> bool {
|
2019-03-26 00:13:09 +01:00
|
|
|
let mut matcher = ty::_match::Match::new(self.tcx(), param_env);
|
2015-03-20 08:17:09 -04:00
|
|
|
matcher.relate(previous, current).is_ok()
|
|
|
|
}
|
|
|
|
|
2019-06-16 12:33:47 +03:00
|
|
|
fn push_stack<'o>(
|
2018-09-07 09:34:09 -04:00
|
|
|
&mut self,
|
2019-06-16 12:33:47 +03:00
|
|
|
previous_stack: TraitObligationStackList<'o, 'tcx>,
|
2018-09-07 09:34:09 -04:00
|
|
|
obligation: &'o TraitObligation<'tcx>,
|
|
|
|
) -> TraitObligationStack<'o, 'tcx> {
|
2021-12-12 12:34:46 +08:00
|
|
|
let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener);
|
2014-10-09 17:19:50 -04:00
|
|
|
|
2019-06-10 16:22:10 -04:00
|
|
|
let dfn = previous_stack.cache.next_dfn();
|
2019-06-10 11:46:53 -04:00
|
|
|
let depth = previous_stack.depth() + 1;
|
2014-12-05 00:03:03 -05:00
|
|
|
TraitObligationStack {
|
2017-07-03 11:19:51 -07:00
|
|
|
obligation,
|
2021-12-12 12:34:46 +08:00
|
|
|
fresh_trait_pred,
|
2019-06-10 11:46:53 -04:00
|
|
|
reached_depth: Cell::new(depth),
|
2015-03-30 17:46:34 -04:00
|
|
|
previous: previous_stack,
|
2019-06-10 16:22:10 -04:00
|
|
|
dfn,
|
2019-06-10 11:46:53 -04:00
|
|
|
depth,
|
2014-09-18 11:08:04 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-20 13:36:04 +00:00
|
|
|
#[instrument(skip(self), level = "debug")]
|
2018-09-07 09:34:09 -04:00
|
|
|
fn closure_trait_ref_unnormalized(
|
|
|
|
&mut self,
|
|
|
|
obligation: &TraitObligation<'tcx>,
|
2019-09-26 22:23:13 +08:00
|
|
|
substs: SubstsRef<'tcx>,
|
2018-09-07 09:34:09 -04:00
|
|
|
) -> ty::PolyTraitRef<'tcx> {
|
2020-03-13 03:23:38 +02:00
|
|
|
let closure_sig = substs.as_closure().sig();
|
2018-04-24 21:45:49 -05:00
|
|
|
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!(?closure_sig);
|
2018-10-03 10:07:16 -04:00
|
|
|
|
2015-01-10 11:54:15 -05:00
|
|
|
// (1) Feels icky to skip the binder here, but OTOH we know
|
|
|
|
// that the self-type is an unboxed closure type and hence is
|
|
|
|
// in fact unparameterized (or at least does not reference any
|
|
|
|
// regions bound in the obligation). Still probably some
|
|
|
|
// refactoring could make this nicer.
|
2020-01-05 20:27:00 +01:00
|
|
|
closure_trait_ref_and_return_type(
|
|
|
|
self.tcx(),
|
|
|
|
obligation.predicate.def_id(),
|
|
|
|
obligation.predicate.skip_binder().self_ty(), // (1)
|
2020-03-18 02:16:01 +02:00
|
|
|
closure_sig,
|
2020-01-05 20:27:00 +01:00
|
|
|
util::TupleArgumentsFlag::No,
|
|
|
|
)
|
|
|
|
.map_bound(|(trait_ref, _)| trait_ref)
|
2015-01-10 11:54:15 -05:00
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
fn generator_trait_ref_unnormalized(
|
|
|
|
&mut self,
|
|
|
|
obligation: &TraitObligation<'tcx>,
|
2019-10-03 21:21:28 +08:00
|
|
|
substs: SubstsRef<'tcx>,
|
2018-09-07 09:34:09 -04:00
|
|
|
) -> ty::PolyTraitRef<'tcx> {
|
2020-03-13 03:23:38 +02:00
|
|
|
let gen_sig = substs.as_generator().poly_sig();
|
2018-04-24 21:45:49 -05:00
|
|
|
|
2016-12-26 14:34:03 +01:00
|
|
|
// (1) Feels icky to skip the binder here, but OTOH we know
|
|
|
|
// that the self-type is an generator type and hence is
|
|
|
|
// in fact unparameterized (or at least does not reference any
|
|
|
|
// regions bound in the obligation). Still probably some
|
|
|
|
// refactoring could make this nicer.
|
|
|
|
|
2020-01-05 20:27:00 +01:00
|
|
|
super::util::generator_trait_ref_and_outputs(
|
|
|
|
self.tcx(),
|
|
|
|
obligation.predicate.def_id(),
|
|
|
|
obligation.predicate.skip_binder().self_ty(), // (1)
|
|
|
|
gen_sig,
|
|
|
|
)
|
|
|
|
.map_bound(|(trait_ref, ..)| trait_ref)
|
2016-12-26 14:34:03 +01:00
|
|
|
}
|
|
|
|
|
2015-02-19 10:30:45 -05:00
|
|
|
/// Returns the obligations that are implied by instantiating an
|
|
|
|
/// impl or trait. The obligations are substituted and fully
|
|
|
|
/// normalized. This is used when confirming an impl or default
|
|
|
|
/// impl.
|
2021-07-16 16:23:42 -04:00
|
|
|
#[tracing::instrument(level = "debug", skip(self, cause, param_env))]
|
2018-09-07 09:34:09 -04:00
|
|
|
fn impl_or_trait_obligations(
|
|
|
|
&mut self,
|
|
|
|
cause: ObligationCause<'tcx>,
|
|
|
|
recursion_depth: usize,
|
|
|
|
param_env: ty::ParamEnv<'tcx>,
|
2019-12-22 17:42:04 -05:00
|
|
|
def_id: DefId, // of impl or trait
|
|
|
|
substs: SubstsRef<'tcx>, // for impl or trait
|
2018-09-07 09:34:09 -04:00
|
|
|
) -> Vec<PredicateObligation<'tcx>> {
|
2015-10-21 19:01:58 +03:00
|
|
|
let tcx = self.tcx();
|
2015-03-26 15:53:00 -04:00
|
|
|
|
2015-10-21 19:01:58 +03:00
|
|
|
// To allow for one-pass evaluation of the nested obligation,
|
|
|
|
// each predicate must be preceded by the obligations required
|
|
|
|
// to normalize it.
|
|
|
|
// for example, if we have:
|
2019-07-31 21:00:35 +02:00
|
|
|
// impl<U: Iterator<Item: Copy>, V: Iterator<Item = U>> Foo for V
|
2015-10-21 19:01:58 +03:00
|
|
|
// the impl will have the following predicates:
|
|
|
|
// <V as Iterator>::Item = U,
|
|
|
|
// U: Iterator, U: Sized,
|
|
|
|
// V: Iterator, V: Sized,
|
|
|
|
// <U as Iterator>::Item: Copy
|
|
|
|
// When we substitute, say, `V => IntoIter<u32>, U => $0`, the last
|
|
|
|
// obligation will normalize to `<$0 as Iterator>::Item = $1` and
|
|
|
|
// `$1: Copy`, so we must ensure the obligations are emitted in
|
|
|
|
// that order.
|
2017-04-24 15:20:46 +03:00
|
|
|
let predicates = tcx.predicates_of(def_id);
|
2021-07-16 16:23:42 -04:00
|
|
|
debug!(?predicates);
|
2016-08-11 09:19:42 +03:00
|
|
|
assert_eq!(predicates.parent, None);
|
2020-02-10 14:28:56 +01:00
|
|
|
let mut obligations = Vec::with_capacity(predicates.predicates.len());
|
2020-01-08 22:06:25 +01:00
|
|
|
for (predicate, _) in predicates.predicates {
|
2021-07-16 16:23:42 -04:00
|
|
|
debug!(?predicate);
|
2020-01-08 22:06:25 +01:00
|
|
|
let predicate = normalize_with_depth_to(
|
|
|
|
self,
|
|
|
|
param_env,
|
|
|
|
cause.clone(),
|
|
|
|
recursion_depth,
|
2020-10-24 02:21:18 +02:00
|
|
|
predicate.subst(tcx, substs),
|
2020-01-08 22:06:25 +01:00
|
|
|
&mut obligations,
|
|
|
|
);
|
|
|
|
obligations.push(Obligation {
|
|
|
|
cause: cause.clone(),
|
|
|
|
recursion_depth,
|
|
|
|
param_env,
|
|
|
|
predicate,
|
|
|
|
});
|
|
|
|
}
|
2018-05-08 11:17:18 +10:00
|
|
|
|
2020-01-08 22:06:25 +01:00
|
|
|
obligations
|
2014-09-12 10:53:35 -04:00
|
|
|
}
|
2016-07-28 18:27:11 +03:00
|
|
|
}
|
2014-12-01 09:23:40 -05:00
|
|
|
|
2020-02-22 11:44:18 +01:00
|
|
|
trait TraitObligationExt<'tcx> {
|
|
|
|
fn derived_cause(
|
|
|
|
&self,
|
|
|
|
variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
|
|
|
|
) -> ObligationCause<'tcx>;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'tcx> TraitObligationExt<'tcx> for TraitObligation<'tcx> {
|
|
|
|
fn derived_cause(
|
2018-09-07 09:34:09 -04:00
|
|
|
&self,
|
|
|
|
variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
|
|
|
|
) -> ObligationCause<'tcx> {
|
2014-12-06 11:39:25 -05:00
|
|
|
/*!
|
|
|
|
* Creates a cause for obligations that are derived from
|
|
|
|
* `obligation` by a recursive search (e.g., for a builtin
|
2017-12-01 10:01:23 -02:00
|
|
|
* bound, or eventually a `auto trait Foo`). If `obligation`
|
2014-12-06 11:39:25 -05:00
|
|
|
* is itself a derived obligation, this is just a clone, but
|
|
|
|
* otherwise we create a "derived obligation" cause so as to
|
|
|
|
* keep track of the original root obligation for error
|
|
|
|
* reporting.
|
|
|
|
*/
|
|
|
|
|
2016-07-28 18:27:11 +03:00
|
|
|
let obligation = self;
|
|
|
|
|
2014-12-23 10:57:44 +01:00
|
|
|
// NOTE(flaper87): As of now, it keeps track of the whole error
|
|
|
|
// chain. Ideally, we should have a way to configure this either
|
|
|
|
// by using -Z verbose or just a CLI argument.
|
2020-01-16 08:27:41 +01:00
|
|
|
let derived_cause = DerivedObligationCause {
|
2021-12-24 22:50:44 +08:00
|
|
|
parent_trait_pred: obligation.predicate,
|
2021-11-11 12:01:12 +11:00
|
|
|
parent_code: obligation.cause.clone_code(),
|
2020-01-16 08:27:41 +01:00
|
|
|
};
|
|
|
|
let derived_code = variant(derived_cause);
|
|
|
|
ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
|
2014-12-06 11:39:25 -05:00
|
|
|
}
|
2014-09-12 10:53:35 -04:00
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
|
|
|
|
fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
|
2015-03-30 17:46:34 -04:00
|
|
|
TraitObligationStackList::with(self)
|
|
|
|
}
|
|
|
|
|
2019-06-10 15:36:38 -04:00
|
|
|
fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> {
|
|
|
|
self.previous.cache
|
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
|
2015-03-30 17:46:34 -04:00
|
|
|
self.list()
|
2014-09-18 11:08:04 -04:00
|
|
|
}
|
2019-06-10 11:46:53 -04:00
|
|
|
|
|
|
|
/// Indicates that attempting to evaluate this stack entry
|
|
|
|
/// required accessing something from the stack at depth `reached_depth`.
|
|
|
|
fn update_reached_depth(&self, reached_depth: usize) {
|
|
|
|
assert!(
|
have on_completion record subcycles
Rework `on_completion` method so that it removes all
provisional cache entries that are "below" a completed
node (while leaving those entries that are not below
the node).
This corrects an imprecise result that could in turn lead
to an incremental compilation failure. Under the old
scheme, if you had:
* A depends on...
* B depends on A
* C depends on...
* D depends on C
* T: 'static
then the provisional results for A, B, C, and D would all
be entangled. Thus, if A was `EvaluatedToOkModuloRegions`
(because of that final condition), then the result for C and
D would also be demoted to "ok modulo regions".
In reality, though, the result for C depends only on C and itself,
and is not dependent on regions. If we happen to evaluate the
cycle starting from C, we would never reach A, and hence the
result would be "ok".
Under the new scheme, the provisional results for C and D
are moved to the permanent cache immediately and are not affected
by the result of A.
2021-05-11 05:40:42 -04:00
|
|
|
self.depth >= reached_depth,
|
2019-06-10 11:46:53 -04:00
|
|
|
"invoked `update_reached_depth` with something under this stack: \
|
|
|
|
self.depth={} reached_depth={}",
|
|
|
|
self.depth,
|
|
|
|
reached_depth,
|
|
|
|
);
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!(reached_depth, "update_reached_depth");
|
2019-06-10 15:35:37 -04:00
|
|
|
let mut p = self;
|
|
|
|
while reached_depth < p.depth {
|
2021-12-12 12:34:46 +08:00
|
|
|
debug!(?p.fresh_trait_pred, "update_reached_depth: marking as cycle participant");
|
2019-06-10 15:35:37 -04:00
|
|
|
p.reached_depth.set(p.reached_depth.get().min(reached_depth));
|
|
|
|
p = p.previous.head.unwrap();
|
|
|
|
}
|
2019-06-10 11:46:53 -04:00
|
|
|
}
|
2014-09-18 11:08:04 -04:00
|
|
|
}
|
|
|
|
|
2019-06-11 19:05:08 -04:00
|
|
|
/// The "provisional evaluation cache" is used to store intermediate cache results
|
|
|
|
/// when solving auto traits. Auto traits are unusual in that they can support
|
|
|
|
/// cycles. So, for example, a "proof tree" like this would be ok:
|
|
|
|
///
|
|
|
|
/// - `Foo<T>: Send` :-
|
|
|
|
/// - `Bar<T>: Send` :-
|
|
|
|
/// - `Foo<T>: Send` -- cycle, but ok
|
|
|
|
/// - `Baz<T>: Send`
|
|
|
|
///
|
|
|
|
/// Here, to prove `Foo<T>: Send`, we have to prove `Bar<T>: Send` and
|
|
|
|
/// `Baz<T>: Send`. Proving `Bar<T>: Send` in turn required `Foo<T>: Send`.
|
|
|
|
/// For non-auto traits, this cycle would be an error, but for auto traits (because
|
|
|
|
/// they are coinductive) it is considered ok.
|
|
|
|
///
|
|
|
|
/// However, there is a complication: at the point where we have
|
|
|
|
/// "proven" `Bar<T>: Send`, we have in fact only proven it
|
|
|
|
/// *provisionally*. In particular, we proved that `Bar<T>: Send`
|
|
|
|
/// *under the assumption* that `Foo<T>: Send`. But what if we later
|
|
|
|
/// find out this assumption is wrong? Specifically, we could
|
|
|
|
/// encounter some kind of error proving `Baz<T>: Send`. In that case,
|
|
|
|
/// `Bar<T>: Send` didn't turn out to be true.
|
|
|
|
///
|
|
|
|
/// In Issue #60010, we found a bug in rustc where it would cache
|
|
|
|
/// these intermediate results. This was fixed in #60444 by disabling
|
|
|
|
/// *all* caching for things involved in a cycle -- in our example,
|
|
|
|
/// that would mean we don't cache that `Bar<T>: Send`. But this led
|
|
|
|
/// to large slowdowns.
|
|
|
|
///
|
|
|
|
/// Specifically, imagine this scenario, where proving `Baz<T>: Send`
|
|
|
|
/// first requires proving `Bar<T>: Send` (which is true:
|
|
|
|
///
|
|
|
|
/// - `Foo<T>: Send` :-
|
|
|
|
/// - `Bar<T>: Send` :-
|
|
|
|
/// - `Foo<T>: Send` -- cycle, but ok
|
|
|
|
/// - `Baz<T>: Send`
|
|
|
|
/// - `Bar<T>: Send` -- would be nice for this to be a cache hit!
|
|
|
|
/// - `*const T: Send` -- but what if we later encounter an error?
|
|
|
|
///
|
|
|
|
/// The *provisional evaluation cache* resolves this issue. It stores
|
|
|
|
/// cache results that we've proven but which were involved in a cycle
|
|
|
|
/// in some way. We track the minimal stack depth (i.e., the
|
|
|
|
/// farthest from the top of the stack) that we are dependent on.
|
|
|
|
/// The idea is that the cache results within are all valid -- so long as
|
|
|
|
/// none of the nodes in between the current node and the node at that minimum
|
|
|
|
/// depth result in an error (in which case the cached results are just thrown away).
|
|
|
|
///
|
|
|
|
/// During evaluation, we consult this provisional cache and rely on
|
|
|
|
/// it. Accessing a cached value is considered equivalent to accessing
|
|
|
|
/// a result at `reached_depth`, so it marks the *current* solution as
|
|
|
|
/// provisional as well. If an error is encountered, we toss out any
|
|
|
|
/// provisional results added from the subtree that encountered the
|
|
|
|
/// error. When we pop the node at `reached_depth` from the stack, we
|
|
|
|
/// can commit all the things that remain in the provisional cache.
|
2019-06-10 15:36:38 -04:00
|
|
|
struct ProvisionalEvaluationCache<'tcx> {
|
2019-06-11 19:05:08 -04:00
|
|
|
/// next "depth first number" to issue -- just a counter
|
2019-06-10 16:22:10 -04:00
|
|
|
dfn: Cell<usize>,
|
2019-06-11 19:05:08 -04:00
|
|
|
|
|
|
|
/// Map from cache key to the provisionally evaluated thing.
|
|
|
|
/// The cache entries contain the result but also the DFN in which they
|
|
|
|
/// were added. The DFN is used to clear out values on failure.
|
|
|
|
///
|
|
|
|
/// Imagine we have a stack like:
|
|
|
|
///
|
|
|
|
/// - `A B C` and we add a cache for the result of C (DFN 2)
|
|
|
|
/// - Then we have a stack `A B D` where `D` has DFN 3
|
|
|
|
/// - We try to solve D by evaluating E: `A B D E` (DFN 4)
|
|
|
|
/// - `E` generates various cache entries which have cyclic dependices on `B`
|
|
|
|
/// - `A B D E F` and so forth
|
|
|
|
/// - the DFN of `F` for example would be 5
|
|
|
|
/// - then we determine that `E` is in error -- we will then clear
|
|
|
|
/// all cache values whose DFN is >= 4 -- in this case, that
|
|
|
|
/// means the cached value for `F`.
|
2021-12-12 12:34:46 +08:00
|
|
|
map: RefCell<FxHashMap<ty::PolyTraitPredicate<'tcx>, ProvisionalEvaluation>>,
|
2019-06-11 19:05:08 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// A cache value for the provisional cache: contains the depth-first
|
|
|
|
/// number (DFN) and result.
|
2019-06-12 10:42:21 -04:00
|
|
|
#[derive(Copy, Clone, Debug)]
|
2019-06-11 19:05:08 -04:00
|
|
|
struct ProvisionalEvaluation {
|
|
|
|
from_dfn: usize,
|
have on_completion record subcycles
Rework `on_completion` method so that it removes all
provisional cache entries that are "below" a completed
node (while leaving those entries that are not below
the node).
This corrects an imprecise result that could in turn lead
to an incremental compilation failure. Under the old
scheme, if you had:
* A depends on...
* B depends on A
* C depends on...
* D depends on C
* T: 'static
then the provisional results for A, B, C, and D would all
be entangled. Thus, if A was `EvaluatedToOkModuloRegions`
(because of that final condition), then the result for C and
D would also be demoted to "ok modulo regions".
In reality, though, the result for C depends only on C and itself,
and is not dependent on regions. If we happen to evaluate the
cycle starting from C, we would never reach A, and hence the
result would be "ok".
Under the new scheme, the provisional results for C and D
are moved to the permanent cache immediately and are not affected
by the result of A.
2021-05-11 05:40:42 -04:00
|
|
|
reached_depth: usize,
|
2019-06-11 19:05:08 -04:00
|
|
|
result: EvaluationResult,
|
Properly track `DepNode`s in trait evaluation provisional cache
Fixes #92987
During evaluation of an auto trait predicate, we may encounter a cycle.
This causes us to store the evaluation result in a special 'provisional
cache;. If we later end up determining that the type can legitimately
implement the auto trait despite the cycle, we remove the entry from
the provisional cache, and insert it into the evaluation cache.
Additionally, trait evaluation creates a special anonymous `DepNode`.
All queries invoked during the predicate evaluation are added as
outoging dependency edges from the `DepNode`. This `DepNode` is then
store in the evaluation cache - if a different query ends up reading
from the cache entry, it will also perform a read of the stored
`DepNode`. As a result, the cached evaluation will still end up
(transitively) incurring all of the same dependencies that it would
if it actually performed the uncached evaluation (e.g. a call to
`type_of` to determine constituent types).
Previously, we did not correctly handle the interaction between the
provisional cache and the created `DepNode`. Storing an evaluation
result in the provisional cache would cause us to lose the `DepNode`
created during the evaluation. If we later moved the entry from the
provisional cache to the evaluation cache, we would use the `DepNode`
associated with the evaluation that caused us to 'complete' the cycle,
not the evaluatoon where we first discovered the cycle. As a result,
future reads from the evaluation cache would miss some incremental
compilation dependencies that would have otherwise been added if the
evaluation was *not* cached.
Under the right circumstances, this could lead to us trying to force
a query with a no-longer-existing `DefPathHash`, since we were missing
the (red) dependency edge that would have caused us to bail out before
attempting forcing.
This commit makes the provisional cache store the `DepNode` create
during the provisional evaluation. When we move an entry from the
provisional cache to the evaluation cache, we create a *new* `DepNode`
that has dependencies going to *both* of the evaluation `DepNodes` we
have available. This ensures that cached reads will incur all of
the necessary dependency edges.
2022-01-18 23:03:55 -05:00
|
|
|
/// The `DepNodeIndex` created for the `evaluate_stack` call for this provisional
|
|
|
|
/// evaluation. When we create an entry in the evaluation cache using this provisional
|
|
|
|
/// cache entry (see `on_completion`), we use this `dep_node` to ensure that future reads from
|
|
|
|
/// the cache will have all of the necessary incr comp dependencies tracked.
|
|
|
|
dep_node: DepNodeIndex,
|
2019-06-10 15:36:38 -04:00
|
|
|
}
|
|
|
|
|
2019-06-12 17:55:10 -04:00
|
|
|
impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> {
|
|
|
|
fn default() -> Self {
|
have on_completion record subcycles
Rework `on_completion` method so that it removes all
provisional cache entries that are "below" a completed
node (while leaving those entries that are not below
the node).
This corrects an imprecise result that could in turn lead
to an incremental compilation failure. Under the old
scheme, if you had:
* A depends on...
* B depends on A
* C depends on...
* D depends on C
* T: 'static
then the provisional results for A, B, C, and D would all
be entangled. Thus, if A was `EvaluatedToOkModuloRegions`
(because of that final condition), then the result for C and
D would also be demoted to "ok modulo regions".
In reality, though, the result for C depends only on C and itself,
and is not dependent on regions. If we happen to evaluate the
cycle starting from C, we would never reach A, and hence the
result would be "ok".
Under the new scheme, the provisional results for C and D
are moved to the permanent cache immediately and are not affected
by the result of A.
2021-05-11 05:40:42 -04:00
|
|
|
Self { dfn: Cell::new(0), map: Default::default() }
|
2019-06-12 17:55:10 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-10 16:22:10 -04:00
|
|
|
impl<'tcx> ProvisionalEvaluationCache<'tcx> {
|
2019-06-11 19:05:08 -04:00
|
|
|
/// Get the next DFN in sequence (basically a counter).
|
2019-06-10 16:22:10 -04:00
|
|
|
fn next_dfn(&self) -> usize {
|
|
|
|
let result = self.dfn.get();
|
|
|
|
self.dfn.set(result + 1);
|
|
|
|
result
|
|
|
|
}
|
2019-06-11 19:05:08 -04:00
|
|
|
|
|
|
|
/// Check the provisional cache for any result for
|
|
|
|
/// `fresh_trait_ref`. If there is a hit, then you must consider
|
|
|
|
/// it an access to the stack slots at depth
|
have on_completion record subcycles
Rework `on_completion` method so that it removes all
provisional cache entries that are "below" a completed
node (while leaving those entries that are not below
the node).
This corrects an imprecise result that could in turn lead
to an incremental compilation failure. Under the old
scheme, if you had:
* A depends on...
* B depends on A
* C depends on...
* D depends on C
* T: 'static
then the provisional results for A, B, C, and D would all
be entangled. Thus, if A was `EvaluatedToOkModuloRegions`
(because of that final condition), then the result for C and
D would also be demoted to "ok modulo regions".
In reality, though, the result for C depends only on C and itself,
and is not dependent on regions. If we happen to evaluate the
cycle starting from C, we would never reach A, and hence the
result would be "ok".
Under the new scheme, the provisional results for C and D
are moved to the permanent cache immediately and are not affected
by the result of A.
2021-05-11 05:40:42 -04:00
|
|
|
/// `reached_depth` (from the returned value).
|
|
|
|
fn get_provisional(
|
|
|
|
&self,
|
2021-12-12 12:34:46 +08:00
|
|
|
fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
|
have on_completion record subcycles
Rework `on_completion` method so that it removes all
provisional cache entries that are "below" a completed
node (while leaving those entries that are not below
the node).
This corrects an imprecise result that could in turn lead
to an incremental compilation failure. Under the old
scheme, if you had:
* A depends on...
* B depends on A
* C depends on...
* D depends on C
* T: 'static
then the provisional results for A, B, C, and D would all
be entangled. Thus, if A was `EvaluatedToOkModuloRegions`
(because of that final condition), then the result for C and
D would also be demoted to "ok modulo regions".
In reality, though, the result for C depends only on C and itself,
and is not dependent on regions. If we happen to evaluate the
cycle starting from C, we would never reach A, and hence the
result would be "ok".
Under the new scheme, the provisional results for C and D
are moved to the permanent cache immediately and are not affected
by the result of A.
2021-05-11 05:40:42 -04:00
|
|
|
) -> Option<ProvisionalEvaluation> {
|
2019-06-12 10:42:21 -04:00
|
|
|
debug!(
|
2021-12-12 12:34:46 +08:00
|
|
|
?fresh_trait_pred,
|
2020-10-11 11:37:56 +01:00
|
|
|
"get_provisional = {:#?}",
|
2021-12-12 12:34:46 +08:00
|
|
|
self.map.borrow().get(&fresh_trait_pred),
|
2019-06-12 10:42:21 -04:00
|
|
|
);
|
2021-12-12 12:34:46 +08:00
|
|
|
Some(*self.map.borrow().get(&fresh_trait_pred)?)
|
2019-06-11 19:05:08 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Insert a provisional result into the cache. The result came
|
|
|
|
/// from the node with the given DFN. It accessed a minimum depth
|
2021-12-12 12:34:46 +08:00
|
|
|
/// of `reached_depth` to compute. It evaluated `fresh_trait_pred`
|
2019-06-11 19:05:08 -04:00
|
|
|
/// and resulted in `result`.
|
|
|
|
fn insert_provisional(
|
|
|
|
&self,
|
|
|
|
from_dfn: usize,
|
|
|
|
reached_depth: usize,
|
2021-12-12 12:34:46 +08:00
|
|
|
fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
|
2019-06-11 19:05:08 -04:00
|
|
|
result: EvaluationResult,
|
Properly track `DepNode`s in trait evaluation provisional cache
Fixes #92987
During evaluation of an auto trait predicate, we may encounter a cycle.
This causes us to store the evaluation result in a special 'provisional
cache;. If we later end up determining that the type can legitimately
implement the auto trait despite the cycle, we remove the entry from
the provisional cache, and insert it into the evaluation cache.
Additionally, trait evaluation creates a special anonymous `DepNode`.
All queries invoked during the predicate evaluation are added as
outoging dependency edges from the `DepNode`. This `DepNode` is then
store in the evaluation cache - if a different query ends up reading
from the cache entry, it will also perform a read of the stored
`DepNode`. As a result, the cached evaluation will still end up
(transitively) incurring all of the same dependencies that it would
if it actually performed the uncached evaluation (e.g. a call to
`type_of` to determine constituent types).
Previously, we did not correctly handle the interaction between the
provisional cache and the created `DepNode`. Storing an evaluation
result in the provisional cache would cause us to lose the `DepNode`
created during the evaluation. If we later moved the entry from the
provisional cache to the evaluation cache, we would use the `DepNode`
associated with the evaluation that caused us to 'complete' the cycle,
not the evaluatoon where we first discovered the cycle. As a result,
future reads from the evaluation cache would miss some incremental
compilation dependencies that would have otherwise been added if the
evaluation was *not* cached.
Under the right circumstances, this could lead to us trying to force
a query with a no-longer-existing `DefPathHash`, since we were missing
the (red) dependency edge that would have caused us to bail out before
attempting forcing.
This commit makes the provisional cache store the `DepNode` create
during the provisional evaluation. When we move an entry from the
provisional cache to the evaluation cache, we create a *new* `DepNode`
that has dependencies going to *both* of the evaluation `DepNodes` we
have available. This ensures that cached reads will incur all of
the necessary dependency edges.
2022-01-18 23:03:55 -05:00
|
|
|
dep_node: DepNodeIndex,
|
2019-06-11 19:05:08 -04:00
|
|
|
) {
|
2021-12-12 12:34:46 +08:00
|
|
|
debug!(?from_dfn, ?fresh_trait_pred, ?result, "insert_provisional");
|
2019-06-11 19:05:08 -04:00
|
|
|
|
have on_completion record subcycles
Rework `on_completion` method so that it removes all
provisional cache entries that are "below" a completed
node (while leaving those entries that are not below
the node).
This corrects an imprecise result that could in turn lead
to an incremental compilation failure. Under the old
scheme, if you had:
* A depends on...
* B depends on A
* C depends on...
* D depends on C
* T: 'static
then the provisional results for A, B, C, and D would all
be entangled. Thus, if A was `EvaluatedToOkModuloRegions`
(because of that final condition), then the result for C and
D would also be demoted to "ok modulo regions".
In reality, though, the result for C depends only on C and itself,
and is not dependent on regions. If we happen to evaluate the
cycle starting from C, we would never reach A, and hence the
result would be "ok".
Under the new scheme, the provisional results for C and D
are moved to the permanent cache immediately and are not affected
by the result of A.
2021-05-11 05:40:42 -04:00
|
|
|
let mut map = self.map.borrow_mut();
|
|
|
|
|
|
|
|
// Subtle: when we complete working on the DFN `from_dfn`, anything
|
|
|
|
// that remains in the provisional cache must be dependent on some older
|
|
|
|
// stack entry than `from_dfn`. We have to update their depth with our transitive
|
|
|
|
// depth in that case or else it would be referring to some popped note.
|
|
|
|
//
|
|
|
|
// Example:
|
|
|
|
// A (reached depth 0)
|
|
|
|
// ...
|
|
|
|
// B // depth 1 -- reached depth = 0
|
|
|
|
// C // depth 2 -- reached depth = 1 (should be 0)
|
|
|
|
// B
|
|
|
|
// A // depth 0
|
|
|
|
// D (reached depth 1)
|
|
|
|
// C (cache -- reached depth = 2)
|
|
|
|
for (_k, v) in &mut *map {
|
|
|
|
if v.from_dfn >= from_dfn {
|
|
|
|
v.reached_depth = reached_depth.min(v.reached_depth);
|
|
|
|
}
|
|
|
|
}
|
2019-06-12 10:42:21 -04:00
|
|
|
|
Properly track `DepNode`s in trait evaluation provisional cache
Fixes #92987
During evaluation of an auto trait predicate, we may encounter a cycle.
This causes us to store the evaluation result in a special 'provisional
cache;. If we later end up determining that the type can legitimately
implement the auto trait despite the cycle, we remove the entry from
the provisional cache, and insert it into the evaluation cache.
Additionally, trait evaluation creates a special anonymous `DepNode`.
All queries invoked during the predicate evaluation are added as
outoging dependency edges from the `DepNode`. This `DepNode` is then
store in the evaluation cache - if a different query ends up reading
from the cache entry, it will also perform a read of the stored
`DepNode`. As a result, the cached evaluation will still end up
(transitively) incurring all of the same dependencies that it would
if it actually performed the uncached evaluation (e.g. a call to
`type_of` to determine constituent types).
Previously, we did not correctly handle the interaction between the
provisional cache and the created `DepNode`. Storing an evaluation
result in the provisional cache would cause us to lose the `DepNode`
created during the evaluation. If we later moved the entry from the
provisional cache to the evaluation cache, we would use the `DepNode`
associated with the evaluation that caused us to 'complete' the cycle,
not the evaluatoon where we first discovered the cycle. As a result,
future reads from the evaluation cache would miss some incremental
compilation dependencies that would have otherwise been added if the
evaluation was *not* cached.
Under the right circumstances, this could lead to us trying to force
a query with a no-longer-existing `DefPathHash`, since we were missing
the (red) dependency edge that would have caused us to bail out before
attempting forcing.
This commit makes the provisional cache store the `DepNode` create
during the provisional evaluation. When we move an entry from the
provisional cache to the evaluation cache, we create a *new* `DepNode`
that has dependencies going to *both* of the evaluation `DepNodes` we
have available. This ensures that cached reads will incur all of
the necessary dependency edges.
2022-01-18 23:03:55 -05:00
|
|
|
map.insert(
|
|
|
|
fresh_trait_pred,
|
|
|
|
ProvisionalEvaluation { from_dfn, reached_depth, result, dep_node },
|
|
|
|
);
|
2019-06-11 19:05:08 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Invoked when the node with dfn `dfn` does not get a successful
|
|
|
|
/// result. This will clear out any provisional cache entries
|
|
|
|
/// that were added since `dfn` was created. This is because the
|
|
|
|
/// provisional entries are things which must assume that the
|
|
|
|
/// things on the stack at the time of their creation succeeded --
|
|
|
|
/// since the failing node is presently at the top of the stack,
|
|
|
|
/// these provisional entries must either depend on it or some
|
|
|
|
/// ancestor of it.
|
|
|
|
fn on_failure(&self, dfn: usize) {
|
2020-10-11 11:37:56 +01:00
|
|
|
debug!(?dfn, "on_failure");
|
2019-06-12 10:42:21 -04:00
|
|
|
self.map.borrow_mut().retain(|key, eval| {
|
|
|
|
if !eval.from_dfn >= dfn {
|
|
|
|
debug!("on_failure: removing {:?}", key);
|
|
|
|
false
|
|
|
|
} else {
|
|
|
|
true
|
|
|
|
}
|
|
|
|
});
|
2019-06-11 19:05:08 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Invoked when the node at depth `depth` completed without
|
|
|
|
/// depending on anything higher in the stack (if that completion
|
|
|
|
/// was a failure, then `on_failure` should have been invoked
|
|
|
|
/// already). The callback `op` will be invoked for each
|
|
|
|
/// provisional entry that we can now confirm.
|
have on_completion record subcycles
Rework `on_completion` method so that it removes all
provisional cache entries that are "below" a completed
node (while leaving those entries that are not below
the node).
This corrects an imprecise result that could in turn lead
to an incremental compilation failure. Under the old
scheme, if you had:
* A depends on...
* B depends on A
* C depends on...
* D depends on C
* T: 'static
then the provisional results for A, B, C, and D would all
be entangled. Thus, if A was `EvaluatedToOkModuloRegions`
(because of that final condition), then the result for C and
D would also be demoted to "ok modulo regions".
In reality, though, the result for C depends only on C and itself,
and is not dependent on regions. If we happen to evaluate the
cycle starting from C, we would never reach A, and hence the
result would be "ok".
Under the new scheme, the provisional results for C and D
are moved to the permanent cache immediately and are not affected
by the result of A.
2021-05-11 05:40:42 -04:00
|
|
|
///
|
|
|
|
/// Note that we may still have provisional cache items remaining
|
|
|
|
/// in the cache when this is done. For example, if there is a
|
|
|
|
/// cycle:
|
|
|
|
///
|
|
|
|
/// * A depends on...
|
|
|
|
/// * B depends on A
|
|
|
|
/// * C depends on...
|
|
|
|
/// * D depends on C
|
|
|
|
/// * ...
|
|
|
|
///
|
|
|
|
/// Then as we complete the C node we will have a provisional cache
|
|
|
|
/// with results for A, B, C, and D. This method would clear out
|
|
|
|
/// the C and D results, but leave A and B provisional.
|
|
|
|
///
|
|
|
|
/// This is determined based on the DFN: we remove any provisional
|
|
|
|
/// results created since `dfn` started (e.g., in our example, dfn
|
|
|
|
/// would be 2, representing the C node, and hence we would
|
|
|
|
/// remove the result for D, which has DFN 3, but not the results for
|
|
|
|
/// A and B, which have DFNs 0 and 1 respectively).
|
2019-06-11 19:05:08 -04:00
|
|
|
fn on_completion(
|
|
|
|
&self,
|
have on_completion record subcycles
Rework `on_completion` method so that it removes all
provisional cache entries that are "below" a completed
node (while leaving those entries that are not below
the node).
This corrects an imprecise result that could in turn lead
to an incremental compilation failure. Under the old
scheme, if you had:
* A depends on...
* B depends on A
* C depends on...
* D depends on C
* T: 'static
then the provisional results for A, B, C, and D would all
be entangled. Thus, if A was `EvaluatedToOkModuloRegions`
(because of that final condition), then the result for C and
D would also be demoted to "ok modulo regions".
In reality, though, the result for C depends only on C and itself,
and is not dependent on regions. If we happen to evaluate the
cycle starting from C, we would never reach A, and hence the
result would be "ok".
Under the new scheme, the provisional results for C and D
are moved to the permanent cache immediately and are not affected
by the result of A.
2021-05-11 05:40:42 -04:00
|
|
|
dfn: usize,
|
Properly track `DepNode`s in trait evaluation provisional cache
Fixes #92987
During evaluation of an auto trait predicate, we may encounter a cycle.
This causes us to store the evaluation result in a special 'provisional
cache;. If we later end up determining that the type can legitimately
implement the auto trait despite the cycle, we remove the entry from
the provisional cache, and insert it into the evaluation cache.
Additionally, trait evaluation creates a special anonymous `DepNode`.
All queries invoked during the predicate evaluation are added as
outoging dependency edges from the `DepNode`. This `DepNode` is then
store in the evaluation cache - if a different query ends up reading
from the cache entry, it will also perform a read of the stored
`DepNode`. As a result, the cached evaluation will still end up
(transitively) incurring all of the same dependencies that it would
if it actually performed the uncached evaluation (e.g. a call to
`type_of` to determine constituent types).
Previously, we did not correctly handle the interaction between the
provisional cache and the created `DepNode`. Storing an evaluation
result in the provisional cache would cause us to lose the `DepNode`
created during the evaluation. If we later moved the entry from the
provisional cache to the evaluation cache, we would use the `DepNode`
associated with the evaluation that caused us to 'complete' the cycle,
not the evaluatoon where we first discovered the cycle. As a result,
future reads from the evaluation cache would miss some incremental
compilation dependencies that would have otherwise been added if the
evaluation was *not* cached.
Under the right circumstances, this could lead to us trying to force
a query with a no-longer-existing `DefPathHash`, since we were missing
the (red) dependency edge that would have caused us to bail out before
attempting forcing.
This commit makes the provisional cache store the `DepNode` create
during the provisional evaluation. When we move an entry from the
provisional cache to the evaluation cache, we create a *new* `DepNode`
that has dependencies going to *both* of the evaluation `DepNodes` we
have available. This ensures that cached reads will incur all of
the necessary dependency edges.
2022-01-18 23:03:55 -05:00
|
|
|
mut op: impl FnMut(ty::PolyTraitPredicate<'tcx>, EvaluationResult, DepNodeIndex),
|
2019-06-11 19:05:08 -04:00
|
|
|
) {
|
have on_completion record subcycles
Rework `on_completion` method so that it removes all
provisional cache entries that are "below" a completed
node (while leaving those entries that are not below
the node).
This corrects an imprecise result that could in turn lead
to an incremental compilation failure. Under the old
scheme, if you had:
* A depends on...
* B depends on A
* C depends on...
* D depends on C
* T: 'static
then the provisional results for A, B, C, and D would all
be entangled. Thus, if A was `EvaluatedToOkModuloRegions`
(because of that final condition), then the result for C and
D would also be demoted to "ok modulo regions".
In reality, though, the result for C depends only on C and itself,
and is not dependent on regions. If we happen to evaluate the
cycle starting from C, we would never reach A, and hence the
result would be "ok".
Under the new scheme, the provisional results for C and D
are moved to the permanent cache immediately and are not affected
by the result of A.
2021-05-11 05:40:42 -04:00
|
|
|
debug!(?dfn, "on_completion");
|
2019-06-12 10:42:21 -04:00
|
|
|
|
2021-12-12 12:34:46 +08:00
|
|
|
for (fresh_trait_pred, eval) in
|
have on_completion record subcycles
Rework `on_completion` method so that it removes all
provisional cache entries that are "below" a completed
node (while leaving those entries that are not below
the node).
This corrects an imprecise result that could in turn lead
to an incremental compilation failure. Under the old
scheme, if you had:
* A depends on...
* B depends on A
* C depends on...
* D depends on C
* T: 'static
then the provisional results for A, B, C, and D would all
be entangled. Thus, if A was `EvaluatedToOkModuloRegions`
(because of that final condition), then the result for C and
D would also be demoted to "ok modulo regions".
In reality, though, the result for C depends only on C and itself,
and is not dependent on regions. If we happen to evaluate the
cycle starting from C, we would never reach A, and hence the
result would be "ok".
Under the new scheme, the provisional results for C and D
are moved to the permanent cache immediately and are not affected
by the result of A.
2021-05-11 05:40:42 -04:00
|
|
|
self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn)
|
|
|
|
{
|
2021-12-12 12:34:46 +08:00
|
|
|
debug!(?fresh_trait_pred, ?eval, "on_completion");
|
2019-06-12 10:42:21 -04:00
|
|
|
|
Properly track `DepNode`s in trait evaluation provisional cache
Fixes #92987
During evaluation of an auto trait predicate, we may encounter a cycle.
This causes us to store the evaluation result in a special 'provisional
cache;. If we later end up determining that the type can legitimately
implement the auto trait despite the cycle, we remove the entry from
the provisional cache, and insert it into the evaluation cache.
Additionally, trait evaluation creates a special anonymous `DepNode`.
All queries invoked during the predicate evaluation are added as
outoging dependency edges from the `DepNode`. This `DepNode` is then
store in the evaluation cache - if a different query ends up reading
from the cache entry, it will also perform a read of the stored
`DepNode`. As a result, the cached evaluation will still end up
(transitively) incurring all of the same dependencies that it would
if it actually performed the uncached evaluation (e.g. a call to
`type_of` to determine constituent types).
Previously, we did not correctly handle the interaction between the
provisional cache and the created `DepNode`. Storing an evaluation
result in the provisional cache would cause us to lose the `DepNode`
created during the evaluation. If we later moved the entry from the
provisional cache to the evaluation cache, we would use the `DepNode`
associated with the evaluation that caused us to 'complete' the cycle,
not the evaluatoon where we first discovered the cycle. As a result,
future reads from the evaluation cache would miss some incremental
compilation dependencies that would have otherwise been added if the
evaluation was *not* cached.
Under the right circumstances, this could lead to us trying to force
a query with a no-longer-existing `DefPathHash`, since we were missing
the (red) dependency edge that would have caused us to bail out before
attempting forcing.
This commit makes the provisional cache store the `DepNode` create
during the provisional evaluation. When we move an entry from the
provisional cache to the evaluation cache, we create a *new* `DepNode`
that has dependencies going to *both* of the evaluation `DepNodes` we
have available. This ensures that cached reads will incur all of
the necessary dependency edges.
2022-01-18 23:03:55 -05:00
|
|
|
op(fresh_trait_pred, eval.result, eval.dep_node);
|
2019-06-11 19:05:08 -04:00
|
|
|
}
|
|
|
|
}
|
2014-09-18 11:08:04 -04:00
|
|
|
}
|
|
|
|
|
2015-03-30 17:46:34 -04:00
|
|
|
#[derive(Copy, Clone)]
|
2019-06-14 19:39:39 +03:00
|
|
|
struct TraitObligationStackList<'o, 'tcx> {
|
2019-06-10 15:36:38 -04:00
|
|
|
cache: &'o ProvisionalEvaluationCache<'tcx>,
|
2018-09-07 09:34:09 -04:00
|
|
|
head: Option<&'o TraitObligationStack<'o, 'tcx>>,
|
2015-03-30 17:46:34 -04:00
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
|
2019-06-10 15:36:38 -04:00
|
|
|
fn empty(cache: &'o ProvisionalEvaluationCache<'tcx>) -> TraitObligationStackList<'o, 'tcx> {
|
|
|
|
TraitObligationStackList { cache, head: None }
|
2015-03-30 17:46:34 -04:00
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
|
2019-06-10 15:36:38 -04:00
|
|
|
TraitObligationStackList { cache: r.cache(), head: Some(r) }
|
2015-03-30 17:46:34 -04:00
|
|
|
}
|
2019-01-02 21:19:03 -05:00
|
|
|
|
|
|
|
fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
|
|
|
|
self.head
|
|
|
|
}
|
2019-06-06 13:32:00 -04:00
|
|
|
|
|
|
|
fn depth(&self) -> usize {
|
move leak-check to during coherence, candidate eval
In particular, it no longer occurs during the subtyping check. This is
important for enabling lazy normalization, because the subtyping check
will be producing sub-obligations that could affect its results.
Consider an example like
for<'a> fn(<&'a as Mirror>::Item) =
fn(&'b u8)
where `<T as Mirror>::Item = T` for all `T`. We will wish to produce a
new subobligation like
<'!1 as Mirror>::Item = &'b u8
This will, after being solved, ultimately yield a constraint that `'!1
= 'b` which will fail. But with the leak-check being performed on
subtyping, there is no opportunity to normalize `<'!1 as
Mirror>::Item` (unless we invoke that normalization directly from
within subtyping, and I would prefer that subtyping and unification
are distinct operations rather than part of the trait solving stack).
The reason to keep the leak check during coherence and trait
evaluation is partly for backwards compatibility. The coherence change
permits impls for `fn(T)` and `fn(&T)` to co-exist, and the trait
evaluation change means that we can distinguish those two cases
without ambiguity errors. It also avoids recreating #57639, where we
were incorrectly choosing a where clause that would have failed the
leak check over the impl which succeeds.
The other reason to keep the leak check in those places is that I
think it is actually close to the model we want. To the point, I think
the trait solver ought to have the job of "breaking down"
higher-ranked region obligation like ``!1: '2` into into region
obligations that operate on things in the root universe, at which
point they should be handed off to polonius. The leak check isn't
*really* doing that -- these obligations are still handed to the
region solver to process -- but if/when we do adopt that model, the
decision to pass/fail would be happening in roughly this part of the
code.
This change had somewhat more side-effects than I anticipated. It
seems like there are cases where the leak-check was not being enforced
during method proving and trait selection. I haven't quite tracked
this down but I think it ought to be documented, so that we know what
precisely we are committing to.
One surprising test was `issue-30786.rs`. The behavior there seems a
bit "fishy" to me, but the problem is not related to the leak check
change as far as I can tell, but more to do with the closure signature
inference code and perhaps the associated type projection, which
together seem to be conspiring to produce an unexpected
signature. Nonetheless, it is an example of where changing the
leak-check can have some unexpected consequences: we're now failing to
resolve a method earlier than we were, which suggests we might change
some method resolutions that would have been ambiguous to be
successful.
TODO:
* figure out remainig test failures
* add new coherence tests for the patterns we ARE disallowing
2020-05-20 10:19:36 +00:00
|
|
|
if let Some(head) = self.head { head.depth } else { 0 }
|
2019-06-06 13:32:00 -04:00
|
|
|
}
|
2015-03-30 17:46:34 -04:00
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
|
|
|
|
type Item = &'o TraitObligationStack<'o, 'tcx>;
|
2015-01-01 23:26:38 -05:00
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
|
2020-10-11 20:52:48 +02:00
|
|
|
let o = self.head?;
|
|
|
|
*self = o.previous;
|
|
|
|
Some(o)
|
2014-09-18 11:08:04 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-07 09:34:09 -04:00
|
|
|
impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
|
2018-08-29 22:02:42 -07:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2015-06-18 08:51:23 +03:00
|
|
|
write!(f, "TraitObligationStack({:?})", self.obligation)
|
2014-09-18 11:08:04 -04:00
|
|
|
}
|
|
|
|
}
|
2022-02-12 13:30:30 -08:00
|
|
|
|
|
|
|
pub enum ProjectionMatchesProjection {
|
|
|
|
Yes,
|
|
|
|
Ambiguous,
|
|
|
|
No,
|
|
|
|
}
|