1 use crate::infer::{InferCtxt, ShallowResolver};
2 use crate::ty::error::ExpectedFound;
3 use crate::ty::{self, ToPolyTraitRef, Ty, TypeFoldable};
4 use rustc_data_structures::obligation_forest::ProcessResult;
5 use rustc_data_structures::obligation_forest::{DoCompleted, Error, ForestObligation};
6 use rustc_data_structures::obligation_forest::{ObligationForest, ObligationProcessor};
7 use std::marker::PhantomData;
9 use super::engine::{TraitEngine, TraitEngineExt};
11 use super::select::SelectionContext;
12 use super::CodeAmbiguity;
13 use super::CodeProjectionError;
14 use super::CodeSelectionError;
15 use super::{ConstEvalFailure, Unimplemented};
16 use super::{FulfillmentError, FulfillmentErrorCode};
17 use super::{ObligationCause, PredicateObligation};
19 impl<'tcx> ForestObligation for PendingPredicateObligation<'tcx> {
20 type Predicate = ty::Predicate<'tcx>;
22 fn as_predicate(&self) -> &Self::Predicate {
23 &self.obligation.predicate
27 /// The fulfillment context is used to drive trait resolution. It
28 /// consists of a list of obligations that must be (eventually)
29 /// satisfied. The job is to track which are satisfied, which yielded
30 /// errors, and which are still pending. At any point, users can call
31 /// `select_where_possible`, and the fulfillment context will try to do
32 /// selection, retaining only those obligations that remain
33 /// ambiguous. This may be helpful in pushing type inference
34 /// along. Once all type inference constraints have been generated, the
35 /// method `select_all_or_error` can be used to report any remaining
36 /// ambiguous cases as errors.
37 pub struct FulfillmentContext<'tcx> {
38 // A list of all obligations that have been registered with this
39 // fulfillment context.
40 predicates: ObligationForest<PendingPredicateObligation<'tcx>>,
41 // Should this fulfillment context register type-lives-for-region
42 // obligations on its parent infcx? In some cases, region
43 // obligations are either already known to hold (normalization) or
44 // hopefully verifed elsewhere (type-impls-bound), and therefore
45 // should not be checked.
47 // Note that if we are normalizing a type that we already
48 // know is well-formed, there should be no harm setting this
49 // to true - all the region variables should be determinable
50 // using the RFC 447 rules, which don't depend on
51 // type-lives-for-region constraints, and because the type
52 // is well-formed, the constraints should hold.
53 register_region_obligations: bool,
54 // Is it OK to register obligations into this infcx inside
57 // The "primary fulfillment" in many cases in typeck lives
58 // outside of any snapshot, so any use of it inside a snapshot
59 // will lead to trouble and therefore is checked against, but
60 // other fulfillment contexts sometimes do live inside of
61 // a snapshot (they don't *straddle* a snapshot, so there
62 // is no trouble there).
63 usable_in_snapshot: bool,
66 #[derive(Clone, Debug)]
67 pub struct PendingPredicateObligation<'tcx> {
68 pub obligation: PredicateObligation<'tcx>,
69 pub stalled_on: Vec<ty::InferTy>,
72 // `PendingPredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
73 #[cfg(target_arch = "x86_64")]
74 static_assert_size!(PendingPredicateObligation<'_>, 136);
76 impl<'a, 'tcx> FulfillmentContext<'tcx> {
77 /// Creates a new fulfillment context.
78 pub fn new() -> FulfillmentContext<'tcx> {
80 predicates: ObligationForest::new(),
81 register_region_obligations: true,
82 usable_in_snapshot: false,
86 pub fn new_in_snapshot() -> FulfillmentContext<'tcx> {
88 predicates: ObligationForest::new(),
89 register_region_obligations: true,
90 usable_in_snapshot: true,
94 pub fn new_ignoring_regions() -> FulfillmentContext<'tcx> {
96 predicates: ObligationForest::new(),
97 register_region_obligations: false,
98 usable_in_snapshot: false,
102 /// Attempts to select obligations using `selcx`.
105 selcx: &mut SelectionContext<'a, 'tcx>,
106 ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
107 debug!("select(obligation-forest-size={})", self.predicates.len());
109 let mut errors = Vec::new();
112 debug!("select: starting another iteration");
114 // Process pending obligations.
115 let outcome = self.predicates.process_obligations(
116 &mut FulfillProcessor {
118 register_region_obligations: self.register_region_obligations,
122 debug!("select: outcome={:#?}", outcome);
124 // FIXME: if we kept the original cache key, we could mark projection
125 // obligations as complete for the projection cache here.
127 errors.extend(outcome.errors.into_iter().map(|e| to_fulfillment_error(e)));
129 // If nothing new was added, no need to keep looping.
136 "select({} predicates remaining, {} errors) done",
137 self.predicates.len(),
141 if errors.is_empty() { Ok(()) } else { Err(errors) }
145 impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> {
146 /// "Normalize" a projection type `<SomeType as SomeTrait>::X` by
147 /// creating a fresh type variable `$0` as well as a projection
148 /// predicate `<SomeType as SomeTrait>::X == $0`. When the
149 /// inference engine runs, it will attempt to find an impl of
150 /// `SomeTrait` or a where-clause that lets us unify `$0` with
151 /// something concrete. If this fails, we'll unify `$0` with
152 /// `projection_ty` again.
153 fn normalize_projection_type(
155 infcx: &InferCtxt<'_, 'tcx>,
156 param_env: ty::ParamEnv<'tcx>,
157 projection_ty: ty::ProjectionTy<'tcx>,
158 cause: ObligationCause<'tcx>,
160 debug!("normalize_projection_type(projection_ty={:?})", projection_ty);
162 debug_assert!(!projection_ty.has_escaping_bound_vars());
164 // FIXME(#20304) -- cache
166 let mut selcx = SelectionContext::new(infcx);
167 let mut obligations = vec![];
168 let normalized_ty = project::normalize_projection_type(
176 self.register_predicate_obligations(infcx, obligations);
178 debug!("normalize_projection_type: result={:?}", normalized_ty);
183 fn register_predicate_obligation(
185 infcx: &InferCtxt<'_, 'tcx>,
186 obligation: PredicateObligation<'tcx>,
188 // this helps to reduce duplicate errors, as well as making
189 // debug output much nicer to read and so on.
190 let obligation = infcx.resolve_vars_if_possible(&obligation);
192 debug!("register_predicate_obligation(obligation={:?})", obligation);
194 assert!(!infcx.is_in_snapshot() || self.usable_in_snapshot);
197 .register_obligation(PendingPredicateObligation { obligation, stalled_on: vec![] });
200 fn select_all_or_error(
202 infcx: &InferCtxt<'_, 'tcx>,
203 ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
204 self.select_where_possible(infcx)?;
206 let errors: Vec<_> = self
208 .to_errors(CodeAmbiguity)
210 .map(|e| to_fulfillment_error(e))
212 if errors.is_empty() { Ok(()) } else { Err(errors) }
215 fn select_where_possible(
217 infcx: &InferCtxt<'_, 'tcx>,
218 ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
219 let mut selcx = SelectionContext::new(infcx);
220 self.select(&mut selcx)
223 fn pending_obligations(&self) -> Vec<PredicateObligation<'tcx>> {
224 self.predicates.map_pending_obligations(|o| o.obligation.clone())
228 struct FulfillProcessor<'a, 'b, 'tcx> {
229 selcx: &'a mut SelectionContext<'b, 'tcx>,
230 register_region_obligations: bool,
233 fn mk_pending(os: Vec<PredicateObligation<'tcx>>) -> Vec<PendingPredicateObligation<'tcx>> {
235 .map(|o| PendingPredicateObligation { obligation: o, stalled_on: vec![] })
239 impl<'a, 'b, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'b, 'tcx> {
240 type Obligation = PendingPredicateObligation<'tcx>;
241 type Error = FulfillmentErrorCode<'tcx>;
243 /// Processes a predicate obligation and returns either:
244 /// - `Changed(v)` if the predicate is true, presuming that `v` are also true
245 /// - `Unchanged` if we don't have enough info to be sure
246 /// - `Error(e)` if the predicate does not hold
248 /// This is always inlined, despite its size, because it has a single
249 /// callsite and it is called *very* frequently.
251 fn process_obligation(
253 pending_obligation: &mut Self::Obligation,
254 ) -> ProcessResult<Self::Obligation, Self::Error> {
255 // If we were stalled on some unresolved variables, first check whether
256 // any of them have been resolved; if not, don't bother doing more work
258 let change = match pending_obligation.stalled_on.len() {
259 // Match arms are in order of frequency, which matters because this
260 // code is so hot. 1 and 0 dominate; 2+ is fairly rare.
262 let infer = pending_obligation.stalled_on[0];
263 ShallowResolver::new(self.selcx.infcx()).shallow_resolve_changed(infer)
266 // In this case we haven't changed, but wish to make a change.
270 // This `for` loop was once a call to `all()`, but this lower-level
271 // form was a perf win. See #64545 for details.
273 for &infer in &pending_obligation.stalled_on {
274 if ShallowResolver::new(self.selcx.infcx()).shallow_resolve_changed(infer) {
285 "process_predicate: pending obligation {:?} still stalled on {:?}",
286 self.selcx.infcx().resolve_vars_if_possible(&pending_obligation.obligation),
287 pending_obligation.stalled_on
289 return ProcessResult::Unchanged;
292 // This part of the code is much colder.
294 pending_obligation.stalled_on.truncate(0);
296 let obligation = &mut pending_obligation.obligation;
298 if obligation.predicate.has_infer_types() {
299 obligation.predicate =
300 self.selcx.infcx().resolve_vars_if_possible(&obligation.predicate);
303 debug!("process_obligation: obligation = {:?} cause = {:?}", obligation, obligation.cause);
305 fn infer_ty(ty: Ty<'tcx>) -> ty::InferTy {
307 ty::Infer(infer) => infer,
312 match obligation.predicate {
313 ty::Predicate::Trait(ref data) => {
314 let trait_obligation = obligation.with(data.clone());
316 if data.is_global() {
317 // no type variables present, can use evaluation for better caching.
318 // FIXME: consider caching errors too.
319 if self.selcx.infcx().predicate_must_hold_considering_regions(&obligation) {
321 "selecting trait `{:?}` at depth {} evaluated to holds",
322 data, obligation.recursion_depth
324 return ProcessResult::Changed(vec![]);
328 match self.selcx.select(&trait_obligation) {
329 Ok(Some(vtable)) => {
331 "selecting trait `{:?}` at depth {} yielded Ok(Some)",
332 data, obligation.recursion_depth
334 ProcessResult::Changed(mk_pending(vtable.nested_obligations()))
338 "selecting trait `{:?}` at depth {} yielded Ok(None)",
339 data, obligation.recursion_depth
342 // This is a bit subtle: for the most part, the
343 // only reason we can fail to make progress on
344 // trait selection is because we don't have enough
345 // information about the types in the trait. One
346 // exception is that we sometimes haven't decided
347 // what kind of closure a closure is. *But*, in
348 // that case, it turns out, the type of the
349 // closure will also change, because the closure
350 // also includes references to its upvars as part
351 // of its type, and those types are resolved at
354 // FIXME(#32286) logic seems false if no upvars
355 pending_obligation.stalled_on =
356 trait_ref_type_vars(self.selcx, data.to_poly_trait_ref());
359 "process_predicate: pending obligation {:?} now stalled on {:?}",
360 self.selcx.infcx().resolve_vars_if_possible(obligation),
361 pending_obligation.stalled_on
364 ProcessResult::Unchanged
366 Err(selection_err) => {
368 "selecting trait `{:?}` at depth {} yielded Err",
369 data, obligation.recursion_depth
372 ProcessResult::Error(CodeSelectionError(selection_err))
377 ty::Predicate::RegionOutlives(ref binder) => {
378 match self.selcx.infcx().region_outlives_predicate(&obligation.cause, binder) {
379 Ok(()) => ProcessResult::Changed(vec![]),
380 Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)),
384 ty::Predicate::TypeOutlives(ref binder) => {
385 // Check if there are higher-ranked vars.
386 match binder.no_bound_vars() {
387 // If there are, inspect the underlying type further.
389 // Convert from `Binder<OutlivesPredicate<Ty, Region>>` to `Binder<Ty>`.
390 let binder = binder.map_bound_ref(|pred| pred.0);
392 // Check if the type has any bound vars.
393 match binder.no_bound_vars() {
394 // If so, this obligation is an error (for now). Eventually we should be
395 // able to support additional cases here, like `for<'a> &'a str: 'a`.
396 // NOTE: this is duplicate-implemented between here and fulfillment.
397 None => ProcessResult::Error(CodeSelectionError(Unimplemented)),
398 // Otherwise, we have something of the form
399 // `for<'a> T: 'a where 'a not in T`, which we can treat as
402 let r_static = self.selcx.tcx().lifetimes.re_static;
403 if self.register_region_obligations {
404 self.selcx.infcx().register_region_obligation_with_cause(
410 ProcessResult::Changed(vec![])
414 // If there aren't, register the obligation.
415 Some(ty::OutlivesPredicate(t_a, r_b)) => {
416 if self.register_region_obligations {
417 self.selcx.infcx().register_region_obligation_with_cause(
423 ProcessResult::Changed(vec![])
428 ty::Predicate::Projection(ref data) => {
429 let project_obligation = obligation.with(data.clone());
430 match project::poly_project_and_unify_type(self.selcx, &project_obligation) {
432 let tcx = self.selcx.tcx();
433 pending_obligation.stalled_on =
434 trait_ref_type_vars(self.selcx, data.to_poly_trait_ref(tcx));
435 ProcessResult::Unchanged
437 Ok(Some(os)) => ProcessResult::Changed(mk_pending(os)),
438 Err(e) => ProcessResult::Error(CodeProjectionError(e)),
442 ty::Predicate::ObjectSafe(trait_def_id) => {
443 if !self.selcx.tcx().is_object_safe(trait_def_id) {
444 ProcessResult::Error(CodeSelectionError(Unimplemented))
446 ProcessResult::Changed(vec![])
450 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
451 match self.selcx.infcx().closure_kind(closure_def_id, closure_substs) {
452 Some(closure_kind) => {
453 if closure_kind.extends(kind) {
454 ProcessResult::Changed(vec![])
456 ProcessResult::Error(CodeSelectionError(Unimplemented))
459 None => ProcessResult::Unchanged,
463 ty::Predicate::WellFormed(ty) => {
464 match ty::wf::obligations(
466 obligation.param_env,
467 obligation.cause.body_id,
469 obligation.cause.span,
472 pending_obligation.stalled_on = vec![infer_ty(ty)];
473 ProcessResult::Unchanged
475 Some(os) => ProcessResult::Changed(mk_pending(os)),
479 ty::Predicate::Subtype(ref subtype) => {
480 match self.selcx.infcx().subtype_predicate(
482 obligation.param_env,
486 // None means that both are unresolved.
487 pending_obligation.stalled_on = vec![
488 infer_ty(subtype.skip_binder().a),
489 infer_ty(subtype.skip_binder().b),
491 ProcessResult::Unchanged
493 Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
495 let expected_found = ExpectedFound::new(
496 subtype.skip_binder().a_is_expected,
497 subtype.skip_binder().a,
498 subtype.skip_binder().b,
500 ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
508 ty::Predicate::ConstEvaluatable(def_id, substs) => {
509 if obligation.param_env.has_local_value() {
510 ProcessResult::Unchanged
512 if !substs.has_local_value() {
513 match self.selcx.tcx().const_eval_resolve(
514 obligation.param_env,
517 Some(obligation.cause.span),
519 Ok(_) => ProcessResult::Changed(vec![]),
521 ProcessResult::Error(CodeSelectionError(ConstEvalFailure(err)))
525 pending_obligation.stalled_on =
526 substs.types().map(|ty| infer_ty(ty)).collect();
527 ProcessResult::Unchanged
534 fn process_backedge<'c, I>(
537 _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>,
539 I: Clone + Iterator<Item = &'c PendingPredicateObligation<'tcx>>,
541 if self.selcx.coinductive_match(cycle.clone().map(|s| s.obligation.predicate)) {
542 debug!("process_child_obligations: coinductive match");
544 let cycle: Vec<_> = cycle.map(|c| c.obligation.clone()).collect();
545 self.selcx.infcx().report_overflow_error_cycle(&cycle);
550 /// Returns the set of type variables contained in a trait ref
551 fn trait_ref_type_vars<'a, 'tcx>(
552 selcx: &mut SelectionContext<'a, 'tcx>,
553 t: ty::PolyTraitRef<'tcx>,
554 ) -> Vec<ty::InferTy> {
555 t.skip_binder() // ok b/c this check doesn't care about regions
557 .map(|t| selcx.infcx().resolve_vars_if_possible(&t))
558 .filter(|t| t.has_infer_types())
559 .flat_map(|t| t.walk())
560 .filter_map(|t| match t.kind {
561 ty::Infer(infer) => Some(infer),
567 fn to_fulfillment_error<'tcx>(
568 error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>,
569 ) -> FulfillmentError<'tcx> {
570 let obligation = error.backtrace.into_iter().next().unwrap().obligation;
571 FulfillmentError::new(obligation, error.error)