1 use crate::infer::{InferCtxt, TyOrConstInferVar};
2 use rustc_data_structures::obligation_forest::ProcessResult;
3 use rustc_data_structures::obligation_forest::{DoCompleted, Error, ForestObligation};
4 use rustc_data_structures::obligation_forest::{ObligationForest, ObligationProcessor};
5 use rustc_errors::ErrorReported;
6 use rustc_infer::traits::{TraitEngine, TraitEngineExt as _, TraitObligation};
7 use rustc_middle::mir::interpret::ErrorHandled;
8 use rustc_middle::ty::error::ExpectedFound;
9 use rustc_middle::ty::ToPredicate;
10 use rustc_middle::ty::{self, Binder, Const, Ty, TypeFoldable};
11 use std::marker::PhantomData;
13 use super::const_evaluatable;
15 use super::select::SelectionContext;
17 use super::CodeAmbiguity;
18 use super::CodeProjectionError;
19 use super::CodeSelectionError;
20 use super::{ConstEvalFailure, Unimplemented};
21 use super::{FulfillmentError, FulfillmentErrorCode};
22 use super::{ObligationCause, PredicateObligation};
24 use crate::traits::error_reporting::InferCtxtExt as _;
25 use crate::traits::project::PolyProjectionObligation;
26 use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
28 impl<'tcx> ForestObligation for PendingPredicateObligation<'tcx> {
29 /// Note that we include both the `ParamEnv` and the `Predicate`,
30 /// as the `ParamEnv` can influence whether fulfillment succeeds
32 type CacheKey = ty::ParamEnvAnd<'tcx, ty::Predicate<'tcx>>;
34 fn as_cache_key(&self) -> Self::CacheKey {
35 self.obligation.param_env.and(self.obligation.predicate)
39 /// The fulfillment context is used to drive trait resolution. It
40 /// consists of a list of obligations that must be (eventually)
41 /// satisfied. The job is to track which are satisfied, which yielded
42 /// errors, and which are still pending. At any point, users can call
43 /// `select_where_possible`, and the fulfillment context will try to do
44 /// selection, retaining only those obligations that remain
45 /// ambiguous. This may be helpful in pushing type inference
46 /// along. Once all type inference constraints have been generated, the
47 /// method `select_all_or_error` can be used to report any remaining
48 /// ambiguous cases as errors.
49 pub struct FulfillmentContext<'tcx> {
50 // A list of all obligations that have been registered with this
51 // fulfillment context.
52 predicates: ObligationForest<PendingPredicateObligation<'tcx>>,
53 // Should this fulfillment context register type-lives-for-region
54 // obligations on its parent infcx? In some cases, region
55 // obligations are either already known to hold (normalization) or
56 // hopefully verifed elsewhere (type-impls-bound), and therefore
57 // should not be checked.
59 // Note that if we are normalizing a type that we already
60 // know is well-formed, there should be no harm setting this
61 // to true - all the region variables should be determinable
62 // using the RFC 447 rules, which don't depend on
63 // type-lives-for-region constraints, and because the type
64 // is well-formed, the constraints should hold.
65 register_region_obligations: bool,
66 // Is it OK to register obligations into this infcx inside
69 // The "primary fulfillment" in many cases in typeck lives
70 // outside of any snapshot, so any use of it inside a snapshot
71 // will lead to trouble and therefore is checked against, but
72 // other fulfillment contexts sometimes do live inside of
73 // a snapshot (they don't *straddle* a snapshot, so there
74 // is no trouble there).
75 usable_in_snapshot: bool,
78 #[derive(Clone, Debug)]
79 pub struct PendingPredicateObligation<'tcx> {
80 pub obligation: PredicateObligation<'tcx>,
81 // This is far more often read than modified, meaning that we
82 // should mostly optimize for reading speed, while modifying is not as relevant.
84 // For whatever reason using a boxed slice is slower than using a `Vec` here.
85 pub stalled_on: Vec<TyOrConstInferVar<'tcx>>,
88 // `PendingPredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
89 #[cfg(target_arch = "x86_64")]
90 static_assert_size!(PendingPredicateObligation<'_>, 56);
92 impl<'a, 'tcx> FulfillmentContext<'tcx> {
93 /// Creates a new fulfillment context.
94 pub fn new() -> FulfillmentContext<'tcx> {
96 predicates: ObligationForest::new(),
97 register_region_obligations: true,
98 usable_in_snapshot: false,
102 pub fn new_in_snapshot() -> FulfillmentContext<'tcx> {
104 predicates: ObligationForest::new(),
105 register_region_obligations: true,
106 usable_in_snapshot: true,
110 pub fn new_ignoring_regions() -> FulfillmentContext<'tcx> {
112 predicates: ObligationForest::new(),
113 register_region_obligations: false,
114 usable_in_snapshot: false,
118 /// Attempts to select obligations using `selcx`.
121 selcx: &mut SelectionContext<'a, 'tcx>,
122 ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
123 debug!("select(obligation-forest-size={})", self.predicates.len());
125 let mut errors = Vec::new();
128 debug!("select: starting another iteration");
130 // Process pending obligations.
131 let outcome = self.predicates.process_obligations(
132 &mut FulfillProcessor {
134 register_region_obligations: self.register_region_obligations,
138 debug!("select: outcome={:#?}", outcome);
140 // FIXME: if we kept the original cache key, we could mark projection
141 // obligations as complete for the projection cache here.
143 errors.extend(outcome.errors.into_iter().map(to_fulfillment_error));
145 // If nothing new was added, no need to keep looping.
152 "select({} predicates remaining, {} errors) done",
153 self.predicates.len(),
157 if errors.is_empty() { Ok(()) } else { Err(errors) }
161 impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> {
162 /// "Normalize" a projection type `<SomeType as SomeTrait>::X` by
163 /// creating a fresh type variable `$0` as well as a projection
164 /// predicate `<SomeType as SomeTrait>::X == $0`. When the
165 /// inference engine runs, it will attempt to find an impl of
166 /// `SomeTrait` or a where-clause that lets us unify `$0` with
167 /// something concrete. If this fails, we'll unify `$0` with
168 /// `projection_ty` again.
169 fn normalize_projection_type(
171 infcx: &InferCtxt<'_, 'tcx>,
172 param_env: ty::ParamEnv<'tcx>,
173 projection_ty: ty::ProjectionTy<'tcx>,
174 cause: ObligationCause<'tcx>,
176 debug!("normalize_projection_type(projection_ty={:?})", projection_ty);
178 debug_assert!(!projection_ty.has_escaping_bound_vars());
180 // FIXME(#20304) -- cache
182 let mut selcx = SelectionContext::new(infcx);
183 let mut obligations = vec![];
184 let normalized_ty = project::normalize_projection_type(
192 self.register_predicate_obligations(infcx, obligations);
194 debug!("normalize_projection_type: result={:?}", normalized_ty);
199 fn register_predicate_obligation(
201 infcx: &InferCtxt<'_, 'tcx>,
202 obligation: PredicateObligation<'tcx>,
204 // this helps to reduce duplicate errors, as well as making
205 // debug output much nicer to read and so on.
206 let obligation = infcx.resolve_vars_if_possible(&obligation);
208 debug!("register_predicate_obligation(obligation={:?})", obligation);
210 assert!(!infcx.is_in_snapshot() || self.usable_in_snapshot);
213 .register_obligation(PendingPredicateObligation { obligation, stalled_on: vec![] });
216 fn select_all_or_error(
218 infcx: &InferCtxt<'_, 'tcx>,
219 ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
220 self.select_where_possible(infcx)?;
222 let errors: Vec<_> = self
224 .to_errors(CodeAmbiguity)
226 .map(to_fulfillment_error)
228 if errors.is_empty() { Ok(()) } else { Err(errors) }
231 fn select_where_possible(
233 infcx: &InferCtxt<'_, 'tcx>,
234 ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
235 let mut selcx = SelectionContext::new(infcx);
236 self.select(&mut selcx)
239 fn pending_obligations(&self) -> Vec<PredicateObligation<'tcx>> {
240 self.predicates.map_pending_obligations(|o| o.obligation.clone())
244 struct FulfillProcessor<'a, 'b, 'tcx> {
245 selcx: &'a mut SelectionContext<'b, 'tcx>,
246 register_region_obligations: bool,
249 fn mk_pending(os: Vec<PredicateObligation<'tcx>>) -> Vec<PendingPredicateObligation<'tcx>> {
251 .map(|o| PendingPredicateObligation { obligation: o, stalled_on: vec![] })
255 impl<'a, 'b, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'b, 'tcx> {
256 type Obligation = PendingPredicateObligation<'tcx>;
257 type Error = FulfillmentErrorCode<'tcx>;
259 /// Processes a predicate obligation and returns either:
260 /// - `Changed(v)` if the predicate is true, presuming that `v` are also true
261 /// - `Unchanged` if we don't have enough info to be sure
262 /// - `Error(e)` if the predicate does not hold
264 /// This is always inlined, despite its size, because it has a single
265 /// callsite and it is called *very* frequently.
267 fn process_obligation(
269 pending_obligation: &mut Self::Obligation,
270 ) -> ProcessResult<Self::Obligation, Self::Error> {
271 // If we were stalled on some unresolved variables, first check whether
272 // any of them have been resolved; if not, don't bother doing more work
274 let change = match pending_obligation.stalled_on.len() {
275 // Match arms are in order of frequency, which matters because this
276 // code is so hot. 1 and 0 dominate; 2+ is fairly rare.
278 let infer_var = pending_obligation.stalled_on[0];
279 self.selcx.infcx().ty_or_const_infer_var_changed(infer_var)
282 // In this case we haven't changed, but wish to make a change.
286 // This `for` loop was once a call to `all()`, but this lower-level
287 // form was a perf win. See #64545 for details.
289 for &infer_var in &pending_obligation.stalled_on {
290 if self.selcx.infcx().ty_or_const_infer_var_changed(infer_var) {
301 "process_predicate: pending obligation {:?} still stalled on {:?}",
302 self.selcx.infcx().resolve_vars_if_possible(&pending_obligation.obligation),
303 pending_obligation.stalled_on
305 return ProcessResult::Unchanged;
308 // This part of the code is much colder.
310 pending_obligation.stalled_on.truncate(0);
312 let obligation = &mut pending_obligation.obligation;
314 if obligation.predicate.has_infer_types_or_consts() {
315 obligation.predicate =
316 self.selcx.infcx().resolve_vars_if_possible(&obligation.predicate);
319 debug!("process_obligation: obligation = {:?} cause = {:?}", obligation, obligation.cause);
321 let infcx = self.selcx.infcx();
323 match obligation.predicate.kind() {
324 ty::PredicateKind::ForAll(binder) => match binder.skip_binder() {
325 // Evaluation will discard candidates using the leak check.
326 // This means we need to pass it the bound version of our
328 ty::PredicateAtom::Trait(trait_ref, _constness) => {
329 let trait_obligation = obligation.with(Binder::bind(trait_ref));
331 self.process_trait_obligation(
334 &mut pending_obligation.stalled_on,
337 ty::PredicateAtom::Projection(data) => {
338 let project_obligation = obligation.with(Binder::bind(data));
340 self.process_projection_obligation(
342 &mut pending_obligation.stalled_on,
345 ty::PredicateAtom::RegionOutlives(_)
346 | ty::PredicateAtom::TypeOutlives(_)
347 | ty::PredicateAtom::WellFormed(_)
348 | ty::PredicateAtom::ObjectSafe(_)
349 | ty::PredicateAtom::ClosureKind(..)
350 | ty::PredicateAtom::Subtype(_)
351 | ty::PredicateAtom::ConstEvaluatable(..)
352 | ty::PredicateAtom::ConstEquate(..) => {
353 let (pred, _) = infcx.replace_bound_vars_with_placeholders(binder);
354 ProcessResult::Changed(mk_pending(vec![
355 obligation.with(pred.to_predicate(self.selcx.tcx())),
358 ty::PredicateAtom::TypeWellFormedFromEnv(..) => {
359 bug!("TypeWellFormedFromEnv is only used for Chalk")
362 &ty::PredicateKind::Atom(atom) => match atom {
363 ty::PredicateAtom::Trait(ref data, _) => {
364 let trait_obligation = obligation.with(Binder::dummy(*data));
366 self.process_trait_obligation(
369 &mut pending_obligation.stalled_on,
373 ty::PredicateAtom::RegionOutlives(data) => {
374 match infcx.region_outlives_predicate(&obligation.cause, Binder::dummy(data)) {
375 Ok(()) => ProcessResult::Changed(vec![]),
376 Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)),
380 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(t_a, r_b)) => {
381 if self.register_region_obligations {
382 self.selcx.infcx().register_region_obligation_with_cause(
388 ProcessResult::Changed(vec![])
391 ty::PredicateAtom::Projection(ref data) => {
392 let project_obligation = obligation.with(Binder::dummy(*data));
394 self.process_projection_obligation(
396 &mut pending_obligation.stalled_on,
400 ty::PredicateAtom::ObjectSafe(trait_def_id) => {
401 if !self.selcx.tcx().is_object_safe(trait_def_id) {
402 ProcessResult::Error(CodeSelectionError(Unimplemented))
404 ProcessResult::Changed(vec![])
408 ty::PredicateAtom::ClosureKind(_, closure_substs, kind) => {
409 match self.selcx.infcx().closure_kind(closure_substs) {
410 Some(closure_kind) => {
411 if closure_kind.extends(kind) {
412 ProcessResult::Changed(vec![])
414 ProcessResult::Error(CodeSelectionError(Unimplemented))
417 None => ProcessResult::Unchanged,
421 ty::PredicateAtom::WellFormed(arg) => {
422 match wf::obligations(
424 obligation.param_env,
425 obligation.cause.body_id,
427 obligation.cause.span,
430 pending_obligation.stalled_on =
431 vec![TyOrConstInferVar::maybe_from_generic_arg(arg).unwrap()];
432 ProcessResult::Unchanged
434 Some(os) => ProcessResult::Changed(mk_pending(os)),
438 ty::PredicateAtom::Subtype(subtype) => {
439 match self.selcx.infcx().subtype_predicate(
441 obligation.param_env,
442 Binder::dummy(subtype),
445 // None means that both are unresolved.
446 pending_obligation.stalled_on = vec![
447 TyOrConstInferVar::maybe_from_ty(subtype.a).unwrap(),
448 TyOrConstInferVar::maybe_from_ty(subtype.b).unwrap(),
450 ProcessResult::Unchanged
452 Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)),
455 ExpectedFound::new(subtype.a_is_expected, subtype.a, subtype.b);
456 ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError(
464 ty::PredicateAtom::ConstEvaluatable(def_id, substs) => {
465 match const_evaluatable::is_const_evaluatable(
469 obligation.param_env,
470 obligation.cause.span,
472 Ok(()) => ProcessResult::Changed(vec![]),
473 Err(e) => ProcessResult::Error(CodeSelectionError(ConstEvalFailure(e))),
477 ty::PredicateAtom::ConstEquate(c1, c2) => {
478 debug!("equating consts: c1={:?} c2={:?}", c1, c2);
480 let stalled_on = &mut pending_obligation.stalled_on;
482 let mut evaluate = |c: &'tcx Const<'tcx>| {
483 if let ty::ConstKind::Unevaluated(def, substs, promoted) = c.val {
484 match self.selcx.infcx().const_eval_resolve(
485 obligation.param_env,
489 Some(obligation.cause.span),
491 Ok(val) => Ok(Const::from_value(self.selcx.tcx(), val, c.ty)),
492 Err(ErrorHandled::TooGeneric) => {
496 .filter_map(|ty| TyOrConstInferVar::maybe_from_ty(ty))
499 Err(ErrorHandled::TooGeneric)
501 Err(err) => Err(err),
508 match (evaluate(c1), evaluate(c2)) {
509 (Ok(c1), Ok(c2)) => {
513 .at(&obligation.cause, obligation.param_env)
516 Ok(_) => ProcessResult::Changed(vec![]),
517 Err(err) => ProcessResult::Error(
518 FulfillmentErrorCode::CodeConstEquateError(
519 ExpectedFound::new(true, c1, c2),
525 (Err(ErrorHandled::Reported(ErrorReported)), _)
526 | (_, Err(ErrorHandled::Reported(ErrorReported))) => {
527 ProcessResult::Error(CodeSelectionError(ConstEvalFailure(
528 ErrorHandled::Reported(ErrorReported),
531 (Err(ErrorHandled::Linted), _) | (_, Err(ErrorHandled::Linted)) => {
533 obligation.cause.span(self.selcx.tcx()),
534 "ConstEquate: const_eval_resolve returned an unexpected error"
537 (Err(ErrorHandled::TooGeneric), _) | (_, Err(ErrorHandled::TooGeneric)) => {
538 ProcessResult::Unchanged
542 ty::PredicateAtom::TypeWellFormedFromEnv(..) => {
543 bug!("TypeWellFormedFromEnv is only used for Chalk")
549 fn process_backedge<'c, I>(
552 _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>,
554 I: Clone + Iterator<Item = &'c PendingPredicateObligation<'tcx>>,
556 if self.selcx.coinductive_match(cycle.clone().map(|s| s.obligation.predicate)) {
557 debug!("process_child_obligations: coinductive match");
559 let cycle: Vec<_> = cycle.map(|c| c.obligation.clone()).collect();
560 self.selcx.infcx().report_overflow_error_cycle(&cycle);
565 impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> {
566 fn process_trait_obligation(
568 obligation: &PredicateObligation<'tcx>,
569 trait_obligation: TraitObligation<'tcx>,
570 stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
571 ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
572 let infcx = self.selcx.infcx();
573 if obligation.predicate.is_global() {
574 // no type variables present, can use evaluation for better caching.
575 // FIXME: consider caching errors too.
576 if infcx.predicate_must_hold_considering_regions(obligation) {
578 "selecting trait `{:?}` at depth {} evaluated to holds",
579 obligation.predicate, obligation.recursion_depth
581 return ProcessResult::Changed(vec![]);
585 match self.selcx.select(&trait_obligation) {
586 Ok(Some(impl_source)) => {
588 "selecting trait `{:?}` at depth {} yielded Ok(Some)",
589 trait_obligation.predicate, obligation.recursion_depth
591 ProcessResult::Changed(mk_pending(impl_source.nested_obligations()))
595 "selecting trait `{:?}` at depth {} yielded Ok(None)",
596 trait_obligation.predicate, obligation.recursion_depth
599 // This is a bit subtle: for the most part, the
600 // only reason we can fail to make progress on
601 // trait selection is because we don't have enough
602 // information about the types in the trait.
603 *stalled_on = trait_ref_infer_vars(
605 trait_obligation.predicate.map_bound(|pred| pred.trait_ref),
609 "process_predicate: pending obligation {:?} now stalled on {:?}",
610 infcx.resolve_vars_if_possible(obligation),
614 ProcessResult::Unchanged
616 Err(selection_err) => {
618 "selecting trait `{:?}` at depth {} yielded Err",
619 trait_obligation.predicate, obligation.recursion_depth
622 ProcessResult::Error(CodeSelectionError(selection_err))
627 fn process_projection_obligation(
629 project_obligation: PolyProjectionObligation<'tcx>,
630 stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>,
631 ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> {
632 let tcx = self.selcx.tcx();
633 match project::poly_project_and_unify_type(self.selcx, &project_obligation) {
634 Ok(Ok(Some(os))) => ProcessResult::Changed(mk_pending(os)),
636 *stalled_on = trait_ref_infer_vars(
638 project_obligation.predicate.to_poly_trait_ref(self.selcx.tcx()),
640 ProcessResult::Unchanged
642 // Let the caller handle the recursion
643 Ok(Err(project::InProgress)) => ProcessResult::Changed(mk_pending(vec![
644 project_obligation.with(project_obligation.predicate.to_predicate(tcx)),
646 Err(e) => ProcessResult::Error(CodeProjectionError(e)),
651 /// Returns the set of inference variables contained in a trait ref.
652 fn trait_ref_infer_vars<'a, 'tcx>(
653 selcx: &mut SelectionContext<'a, 'tcx>,
654 trait_ref: ty::PolyTraitRef<'tcx>,
655 ) -> Vec<TyOrConstInferVar<'tcx>> {
658 .resolve_vars_if_possible(&trait_ref)
662 // FIXME(eddyb) try using `skip_current_subtree` to skip everything that
663 // doesn't contain inference variables, not just the outermost level.
664 .filter(|arg| arg.has_infer_types_or_consts())
665 .flat_map(|arg| arg.walk())
666 .filter_map(TyOrConstInferVar::maybe_from_generic_arg)
670 fn to_fulfillment_error<'tcx>(
671 error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>,
672 ) -> FulfillmentError<'tcx> {
673 let obligation = error.backtrace.into_iter().next().unwrap().obligation;
674 FulfillmentError::new(obligation, error.error)