1 use crate::infer::{InferCtxt, ShallowResolver};
2 use crate::ty::{self, Ty, TypeFoldable, ToPolyTraitRef};
3 use crate::ty::error::ExpectedFound;
4 use rustc_data_structures::obligation_forest::{DoCompleted, Error, ForestObligation};
5 use rustc_data_structures::obligation_forest::{ObligationForest, ObligationProcessor};
6 use rustc_data_structures::obligation_forest::{ProcessResult};
7 use std::marker::PhantomData;
9 use super::CodeAmbiguity;
10 use super::CodeProjectionError;
11 use super::CodeSelectionError;
12 use super::engine::{TraitEngine, TraitEngineExt};
13 use super::{FulfillmentError, FulfillmentErrorCode};
14 use super::{ObligationCause, PredicateObligation};
16 use super::select::SelectionContext;
17 use super::{Unimplemented, ConstEvalFailure};
19 impl<'tcx> ForestObligation for PendingPredicateObligation<'tcx> {
20 type Predicate = ty::Predicate<'tcx>;
22 fn as_predicate(&self) -> &Self::Predicate { &self.obligation.predicate }
25 /// The fulfillment context is used to drive trait resolution. It
26 /// consists of a list of obligations that must be (eventually)
27 /// satisfied. The job is to track which are satisfied, which yielded
28 /// errors, and which are still pending. At any point, users can call
29 /// `select_where_possible`, and the fulfillment context will try to do
30 /// selection, retaining only those obligations that remain
31 /// ambiguous. This may be helpful in pushing type inference
32 /// along. Once all type inference constraints have been generated, the
33 /// method `select_all_or_error` can be used to report any remaining
34 /// ambiguous cases as errors.
35 pub struct FulfillmentContext<'tcx> {
36 // A list of all obligations that have been registered with this
37 // fulfillment context.
38 predicates: ObligationForest<PendingPredicateObligation<'tcx>>,
39 // Should this fulfillment context register type-lives-for-region
40 // obligations on its parent infcx? In some cases, region
41 // obligations are either already known to hold (normalization) or
42 // hopefully verifed elsewhere (type-impls-bound), and therefore
43 // should not be checked.
45 // Note that if we are normalizing a type that we already
46 // know is well-formed, there should be no harm setting this
47 // to true - all the region variables should be determinable
48 // using the RFC 447 rules, which don't depend on
49 // type-lives-for-region constraints, and because the type
50 // is well-formed, the constraints should hold.
51 register_region_obligations: bool,
52 // Is it OK to register obligations into this infcx inside
55 // The "primary fulfillment" in many cases in typeck lives
56 // outside of any snapshot, so any use of it inside a snapshot
57 // will lead to trouble and therefore is checked against, but
58 // other fulfillment contexts sometimes do live inside of
59 // a snapshot (they don't *straddle* a snapshot, so there
60 // is no trouble there).
61 usable_in_snapshot: bool
64 #[derive(Clone, Debug)]
65 pub struct PendingPredicateObligation<'tcx> {
66 pub obligation: PredicateObligation<'tcx>,
67 pub stalled_on: Vec<ty::InferTy>,
70 // `PendingPredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
71 #[cfg(target_arch = "x86_64")]
72 static_assert_size!(PendingPredicateObligation<'_>, 136);
74 impl<'a, 'tcx> FulfillmentContext<'tcx> {
75 /// Creates a new fulfillment context.
76 pub fn new() -> FulfillmentContext<'tcx> {
78 predicates: ObligationForest::new(),
79 register_region_obligations: true,
80 usable_in_snapshot: false,
84 pub fn new_in_snapshot() -> FulfillmentContext<'tcx> {
86 predicates: ObligationForest::new(),
87 register_region_obligations: true,
88 usable_in_snapshot: true,
92 pub fn new_ignoring_regions() -> FulfillmentContext<'tcx> {
94 predicates: ObligationForest::new(),
95 register_region_obligations: false,
96 usable_in_snapshot: false
100 /// Attempts to select obligations using `selcx`.
103 selcx: &mut SelectionContext<'a, 'tcx>,
104 ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
105 debug!("select(obligation-forest-size={})", self.predicates.len());
107 let mut errors = Vec::new();
110 debug!("select: starting another iteration");
112 // Process pending obligations.
113 let outcome = self.predicates.process_obligations(&mut FulfillProcessor {
115 register_region_obligations: self.register_region_obligations
117 debug!("select: outcome={:#?}", outcome);
119 // FIXME: if we kept the original cache key, we could mark projection
120 // obligations as complete for the projection cache here.
123 outcome.errors.into_iter()
124 .map(|e| to_fulfillment_error(e)));
126 // If nothing new was added, no need to keep looping.
132 debug!("select({} predicates remaining, {} errors) done",
133 self.predicates.len(), errors.len());
135 if errors.is_empty() {
143 impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> {
144 /// "Normalize" a projection type `<SomeType as SomeTrait>::X` by
145 /// creating a fresh type variable `$0` as well as a projection
146 /// predicate `<SomeType as SomeTrait>::X == $0`. When the
147 /// inference engine runs, it will attempt to find an impl of
148 /// `SomeTrait` or a where-clause that lets us unify `$0` with
149 /// something concrete. If this fails, we'll unify `$0` with
150 /// `projection_ty` again.
151 fn normalize_projection_type(
153 infcx: &InferCtxt<'_, 'tcx>,
154 param_env: ty::ParamEnv<'tcx>,
155 projection_ty: ty::ProjectionTy<'tcx>,
156 cause: ObligationCause<'tcx>,
158 debug!("normalize_projection_type(projection_ty={:?})",
161 debug_assert!(!projection_ty.has_escaping_bound_vars());
163 // FIXME(#20304) -- cache
165 let mut selcx = SelectionContext::new(infcx);
166 let mut obligations = vec![];
167 let normalized_ty = project::normalize_projection_type(&mut selcx,
173 self.register_predicate_obligations(infcx, obligations);
175 debug!("normalize_projection_type: result={:?}", normalized_ty);
180 fn register_predicate_obligation(
182 infcx: &InferCtxt<'_, 'tcx>,
183 obligation: PredicateObligation<'tcx>,
185 // this helps to reduce duplicate errors, as well as making
186 // debug output much nicer to read and so on.
187 let obligation = infcx.resolve_vars_if_possible(&obligation);
189 debug!("register_predicate_obligation(obligation={:?})", obligation);
191 assert!(!infcx.is_in_snapshot() || self.usable_in_snapshot);
193 self.predicates.register_obligation(PendingPredicateObligation {
199 fn select_all_or_error(
201 infcx: &InferCtxt<'_, 'tcx>,
202 ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
203 self.select_where_possible(infcx)?;
206 self.predicates.to_errors(CodeAmbiguity)
208 .map(|e| to_fulfillment_error(e))
210 if errors.is_empty() {
217 fn select_where_possible(
219 infcx: &InferCtxt<'_, 'tcx>,
220 ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
221 let mut selcx = SelectionContext::new(infcx);
222 self.select(&mut selcx)
225 fn pending_obligations(&self) -> Vec<PredicateObligation<'tcx>> {
226 self.predicates.map_pending_obligations(|o| o.obligation.clone())
230 struct FulfillProcessor<'a, 'b, 'tcx> {
231 selcx: &'a mut SelectionContext<'b, 'tcx>,
232 register_region_obligations: bool,
235 fn mk_pending(os: Vec<PredicateObligation<'tcx>>) -> Vec<PendingPredicateObligation<'tcx>> {
236 os.into_iter().map(|o| PendingPredicateObligation {
242 impl<'a, 'b, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'b, 'tcx> {
243 type Obligation = PendingPredicateObligation<'tcx>;
244 type Error = FulfillmentErrorCode<'tcx>;
246 /// Processes a predicate obligation and returns either:
247 /// - `Changed(v)` if the predicate is true, presuming that `v` are also true
248 /// - `Unchanged` if we don't have enough info to be sure
249 /// - `Error(e)` if the predicate does not hold
251 /// This is always inlined, despite its size, because it has a single
252 /// callsite and it is called *very* frequently.
254 fn process_obligation(
256 pending_obligation: &mut Self::Obligation,
257 ) -> ProcessResult<Self::Obligation, Self::Error> {
258 // If we were stalled on some unresolved variables, first check whether
259 // any of them have been resolved; if not, don't bother doing more work
261 let change = match pending_obligation.stalled_on.len() {
262 // Match arms are in order of frequency, which matters because this
263 // code is so hot. 1 and 0 dominate; 2+ is fairly rare.
265 let infer = pending_obligation.stalled_on[0];
266 ShallowResolver::new(self.selcx.infcx()).shallow_resolve_changed(infer)
269 // In this case we haven't changed, but wish to make a change.
273 // This `for` loop was once a call to `all()`, but this lower-level
274 // form was a perf win. See #64545 for details.
276 for &infer in &pending_obligation.stalled_on {
277 if ShallowResolver::new(self.selcx.infcx()).shallow_resolve_changed(infer) {
287 debug!("process_predicate: pending obligation {:?} still stalled on {:?}",
289 .resolve_vars_if_possible(&pending_obligation.obligation),
290 pending_obligation.stalled_on);
291 return ProcessResult::Unchanged;
294 // This part of the code is much colder.
296 pending_obligation.stalled_on.truncate(0);
298 let obligation = &mut pending_obligation.obligation;
300 if obligation.predicate.has_infer_types() {
301 obligation.predicate =
302 self.selcx.infcx().resolve_vars_if_possible(&obligation.predicate);
305 debug!("process_obligation: obligation = {:?} cause = {:?}", obligation, obligation.cause);
307 fn infer_ty(ty: Ty<'tcx>) -> ty::InferTy {
309 ty::Infer(infer) => infer,
314 match obligation.predicate {
315 ty::Predicate::Trait(ref data) => {
316 let trait_obligation = obligation.with(data.clone());
318 if data.is_global() {
319 // no type variables present, can use evaluation for better caching.
320 // FIXME: consider caching errors too.
321 if self.selcx.infcx().predicate_must_hold_considering_regions(&obligation) {
322 debug!("selecting trait `{:?}` at depth {} evaluated to holds",
323 data, obligation.recursion_depth);
324 return ProcessResult::Changed(vec![])
328 match self.selcx.select(&trait_obligation) {
329 Ok(Some(vtable)) => {
330 debug!("selecting trait `{:?}` at depth {} yielded Ok(Some)",
331 data, obligation.recursion_depth);
332 ProcessResult::Changed(mk_pending(vtable.nested_obligations()))
335 debug!("selecting trait `{:?}` at depth {} yielded Ok(None)",
336 data, obligation.recursion_depth);
338 // This is a bit subtle: for the most part, the
339 // only reason we can fail to make progress on
340 // trait selection is because we don't have enough
341 // information about the types in the trait. One
342 // exception is that we sometimes haven't decided
343 // what kind of closure a closure is. *But*, in
344 // that case, it turns out, the type of the
345 // closure will also change, because the closure
346 // also includes references to its upvars as part
347 // of its type, and those types are resolved at
350 // FIXME(#32286) logic seems false if no upvars
351 pending_obligation.stalled_on =
352 trait_ref_type_vars(self.selcx, data.to_poly_trait_ref());
354 debug!("process_predicate: pending obligation {:?} now stalled on {:?}",
355 self.selcx.infcx().resolve_vars_if_possible(obligation),
356 pending_obligation.stalled_on);
358 ProcessResult::Unchanged
360 Err(selection_err) => {
361 info!("selecting trait `{:?}` at depth {} yielded Err",
362 data, obligation.recursion_depth);
364 ProcessResult::Error(CodeSelectionError(selection_err))
369 ty::Predicate::RegionOutlives(ref binder) => {
370 match self.selcx.infcx().region_outlives_predicate(&obligation.cause, binder) {
371 Ok(()) => ProcessResult::Changed(vec![]),
372 Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)),
376 ty::Predicate::TypeOutlives(ref binder) => {
377 // Check if there are higher-ranked vars.
378 match binder.no_bound_vars() {
379 // If there are, inspect the underlying type further.
381 // Convert from `Binder<OutlivesPredicate<Ty, Region>>` to `Binder<Ty>`.
382 let binder = binder.map_bound_ref(|pred| pred.0);
384 // Check if the type has any bound vars.
385 match binder.no_bound_vars() {
386 // If so, this obligation is an error (for now). Eventually we should be
387 // able to support additional cases here, like `for<'a> &'a str: 'a`.
388 // NOTE: this is duplicate-implemented between here and fulfillment.
390 ProcessResult::Error(CodeSelectionError(Unimplemented))
392 // Otherwise, we have something of the form
393 // `for<'a> T: 'a where 'a not in T`, which we can treat as
396 let r_static = self.selcx.tcx().lifetimes.re_static;
397 if self.register_region_obligations {
398 self.selcx.infcx().register_region_obligation_with_cause(
404 ProcessResult::Changed(vec![])
408 // If there aren't, register the obligation.
409 Some(ty::OutlivesPredicate(t_a, r_b)) => {
410 if self.register_region_obligations {
411 self.selcx.infcx().register_region_obligation_with_cause(
417 ProcessResult::Changed(vec![])
422 ty::Predicate::Projection(ref data) => {
423 let project_obligation = obligation.with(data.clone());
424 match project::poly_project_and_unify_type(self.selcx, &project_obligation) {
426 let tcx = self.selcx.tcx();
427 pending_obligation.stalled_on =
428 trait_ref_type_vars(self.selcx, data.to_poly_trait_ref(tcx));
429 ProcessResult::Unchanged
431 Ok(Some(os)) => ProcessResult::Changed(mk_pending(os)),
432 Err(e) => ProcessResult::Error(CodeProjectionError(e))
436 ty::Predicate::ObjectSafe(trait_def_id) => {
437 if !self.selcx.tcx().is_object_safe(trait_def_id) {
438 ProcessResult::Error(CodeSelectionError(Unimplemented))
440 ProcessResult::Changed(vec![])
444 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
445 match self.selcx.infcx().closure_kind(closure_def_id, closure_substs) {
446 Some(closure_kind) => {
447 if closure_kind.extends(kind) {
448 ProcessResult::Changed(vec![])
450 ProcessResult::Error(CodeSelectionError(Unimplemented))
454 ProcessResult::Unchanged
459 ty::Predicate::WellFormed(ty) => {
460 match ty::wf::obligations(
462 obligation.param_env,
463 obligation.cause.body_id,
465 obligation.cause.span,
468 pending_obligation.stalled_on = vec![infer_ty(ty)];
469 ProcessResult::Unchanged
471 Some(os) => ProcessResult::Changed(mk_pending(os))
475 ty::Predicate::Subtype(ref subtype) => {
476 match self.selcx.infcx().subtype_predicate(&obligation.cause,
477 obligation.param_env,
480 // None means that both are unresolved.
481 pending_obligation.stalled_on = vec![infer_ty(subtype.skip_binder().a),
482 infer_ty(subtype.skip_binder().b)];
483 ProcessResult::Unchanged
486 ProcessResult::Changed(mk_pending(ok.obligations))
489 let expected_found = ExpectedFound::new(subtype.skip_binder().a_is_expected,
490 subtype.skip_binder().a,
491 subtype.skip_binder().b);
492 ProcessResult::Error(
493 FulfillmentErrorCode::CodeSubtypeError(expected_found, err))
498 ty::Predicate::ConstEvaluatable(def_id, substs) => {
499 if obligation.param_env.has_local_value() {
500 ProcessResult::Unchanged
502 if !substs.has_local_value() {
503 match self.selcx.tcx().const_eval_resolve(obligation.param_env,
506 Some(obligation.cause.span)) {
507 Ok(_) => ProcessResult::Changed(vec![]),
508 Err(err) => ProcessResult::Error(
509 CodeSelectionError(ConstEvalFailure(err)))
512 pending_obligation.stalled_on =
513 substs.types().map(|ty| infer_ty(ty)).collect();
514 ProcessResult::Unchanged
521 fn process_backedge<'c, I>(&mut self, cycle: I,
522 _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>)
523 where I: Clone + Iterator<Item=&'c PendingPredicateObligation<'tcx>>,
525 if self.selcx.coinductive_match(cycle.clone().map(|s| s.obligation.predicate)) {
526 debug!("process_child_obligations: coinductive match");
528 let cycle: Vec<_> = cycle.map(|c| c.obligation.clone()).collect();
529 self.selcx.infcx().report_overflow_error_cycle(&cycle);
534 /// Returns the set of type variables contained in a trait ref
535 fn trait_ref_type_vars<'a, 'tcx>(
536 selcx: &mut SelectionContext<'a, 'tcx>,
537 t: ty::PolyTraitRef<'tcx>,
538 ) -> Vec<ty::InferTy> {
539 t.skip_binder() // ok b/c this check doesn't care about regions
541 .map(|t| selcx.infcx().resolve_vars_if_possible(&t))
542 .filter(|t| t.has_infer_types())
543 .flat_map(|t| t.walk())
544 .filter_map(|t| match t.kind { ty::Infer(infer) => Some(infer), _ => None })
548 fn to_fulfillment_error<'tcx>(
549 error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>)
550 -> FulfillmentError<'tcx>
552 let obligation = error.backtrace.into_iter().next().unwrap().obligation;
553 FulfillmentError::new(obligation, error.error)