1 use crate::infer::{InferCtxt, ShallowResolver};
2 use crate::mir::interpret::{GlobalId, ErrorHandled};
3 use crate::ty::{self, Ty, TypeFoldable, ToPolyTraitRef};
4 use crate::ty::error::ExpectedFound;
5 use rustc_data_structures::obligation_forest::{DoCompleted, Error, ForestObligation};
6 use rustc_data_structures::obligation_forest::{ObligationForest, ObligationProcessor};
7 use rustc_data_structures::obligation_forest::{ProcessResult};
8 use std::marker::PhantomData;
10 use super::CodeAmbiguity;
11 use super::CodeProjectionError;
12 use super::CodeSelectionError;
13 use super::engine::{TraitEngine, TraitEngineExt};
14 use super::{FulfillmentError, FulfillmentErrorCode};
15 use super::{ObligationCause, PredicateObligation};
17 use super::select::SelectionContext;
18 use super::{Unimplemented, ConstEvalFailure};
20 impl<'tcx> ForestObligation for PendingPredicateObligation<'tcx> {
21 type Predicate = ty::Predicate<'tcx>;
23 fn as_predicate(&self) -> &Self::Predicate { &self.obligation.predicate }
26 /// The fulfillment context is used to drive trait resolution. It
27 /// consists of a list of obligations that must be (eventually)
28 /// satisfied. The job is to track which are satisfied, which yielded
29 /// errors, and which are still pending. At any point, users can call
30 /// `select_where_possible`, and the fulfillment context will try to do
31 /// selection, retaining only those obligations that remain
32 /// ambiguous. This may be helpful in pushing type inference
33 /// along. Once all type inference constraints have been generated, the
34 /// method `select_all_or_error` can be used to report any remaining
35 /// ambiguous cases as errors.
36 pub struct FulfillmentContext<'tcx> {
37 // A list of all obligations that have been registered with this
38 // fulfillment context.
39 predicates: ObligationForest<PendingPredicateObligation<'tcx>>,
40 // Should this fulfillment context register type-lives-for-region
41 // obligations on its parent infcx? In some cases, region
42 // obligations are either already known to hold (normalization) or
43 // hopefully verifed elsewhere (type-impls-bound), and therefore
44 // should not be checked.
46 // Note that if we are normalizing a type that we already
47 // know is well-formed, there should be no harm setting this
48 // to true - all the region variables should be determinable
49 // using the RFC 447 rules, which don't depend on
50 // type-lives-for-region constraints, and because the type
51 // is well-formed, the constraints should hold.
52 register_region_obligations: bool,
53 // Is it OK to register obligations into this infcx inside
56 // The "primary fulfillment" in many cases in typeck lives
57 // outside of any snapshot, so any use of it inside a snapshot
58 // will lead to trouble and therefore is checked against, but
59 // other fulfillment contexts sometimes do live inside of
60 // a snapshot (they don't *straddle* a snapshot, so there
61 // is no trouble there).
62 usable_in_snapshot: bool
65 #[derive(Clone, Debug)]
66 pub struct PendingPredicateObligation<'tcx> {
67 pub obligation: PredicateObligation<'tcx>,
68 pub stalled_on: Vec<Ty<'tcx>>,
71 // `PendingPredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger.
72 #[cfg(target_arch = "x86_64")]
73 static_assert_size!(PendingPredicateObligation<'_>, 136);
75 impl<'a, 'tcx> FulfillmentContext<'tcx> {
76 /// Creates a new fulfillment context.
77 pub fn new() -> FulfillmentContext<'tcx> {
79 predicates: ObligationForest::new(),
80 register_region_obligations: true,
81 usable_in_snapshot: false,
85 pub fn new_in_snapshot() -> FulfillmentContext<'tcx> {
87 predicates: ObligationForest::new(),
88 register_region_obligations: true,
89 usable_in_snapshot: true,
93 pub fn new_ignoring_regions() -> FulfillmentContext<'tcx> {
95 predicates: ObligationForest::new(),
96 register_region_obligations: false,
97 usable_in_snapshot: false
101 /// Attempts to select obligations using `selcx`.
104 selcx: &mut SelectionContext<'a, 'tcx>,
105 ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
106 debug!("select(obligation-forest-size={})", self.predicates.len());
108 let mut errors = Vec::new();
111 debug!("select: starting another iteration");
113 // Process pending obligations.
114 let outcome = self.predicates.process_obligations(&mut FulfillProcessor {
116 register_region_obligations: self.register_region_obligations
118 debug!("select: outcome={:#?}", outcome);
120 // FIXME: if we kept the original cache key, we could mark projection
121 // obligations as complete for the projection cache here.
124 outcome.errors.into_iter()
125 .map(|e| to_fulfillment_error(e)));
127 // If nothing new was added, no need to keep looping.
133 debug!("select({} predicates remaining, {} errors) done",
134 self.predicates.len(), errors.len());
136 if errors.is_empty() {
144 impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> {
145 /// "Normalize" a projection type `<SomeType as SomeTrait>::X` by
146 /// creating a fresh type variable `$0` as well as a projection
147 /// predicate `<SomeType as SomeTrait>::X == $0`. When the
148 /// inference engine runs, it will attempt to find an impl of
149 /// `SomeTrait` or a where-clause that lets us unify `$0` with
150 /// something concrete. If this fails, we'll unify `$0` with
151 /// `projection_ty` again.
152 fn normalize_projection_type(
154 infcx: &InferCtxt<'_, 'tcx>,
155 param_env: ty::ParamEnv<'tcx>,
156 projection_ty: ty::ProjectionTy<'tcx>,
157 cause: ObligationCause<'tcx>,
159 debug!("normalize_projection_type(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(&mut selcx,
174 self.register_predicate_obligations(infcx, obligations);
176 debug!("normalize_projection_type: result={:?}", normalized_ty);
181 fn register_predicate_obligation(
183 infcx: &InferCtxt<'_, 'tcx>,
184 obligation: PredicateObligation<'tcx>,
186 // this helps to reduce duplicate errors, as well as making
187 // debug output much nicer to read and so on.
188 let obligation = infcx.resolve_vars_if_possible(&obligation);
190 debug!("register_predicate_obligation(obligation={:?})", obligation);
192 assert!(!infcx.is_in_snapshot() || self.usable_in_snapshot);
194 self.predicates.register_obligation(PendingPredicateObligation {
200 fn select_all_or_error(
202 infcx: &InferCtxt<'_, 'tcx>,
203 ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
204 self.select_where_possible(infcx)?;
207 self.predicates.to_errors(CodeAmbiguity)
209 .map(|e| to_fulfillment_error(e))
211 if errors.is_empty() {
218 fn select_where_possible(
220 infcx: &InferCtxt<'_, 'tcx>,
221 ) -> Result<(), Vec<FulfillmentError<'tcx>>> {
222 let mut selcx = SelectionContext::new(infcx);
223 self.select(&mut selcx)
226 fn pending_obligations(&self) -> Vec<PredicateObligation<'tcx>> {
227 self.predicates.map_pending_obligations(|o| o.obligation.clone())
231 struct FulfillProcessor<'a, 'b, 'tcx> {
232 selcx: &'a mut SelectionContext<'b, 'tcx>,
233 register_region_obligations: bool,
236 fn mk_pending(os: Vec<PredicateObligation<'tcx>>) -> Vec<PendingPredicateObligation<'tcx>> {
237 os.into_iter().map(|o| PendingPredicateObligation {
243 impl<'a, 'b, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'b, 'tcx> {
244 type Obligation = PendingPredicateObligation<'tcx>;
245 type Error = FulfillmentErrorCode<'tcx>;
247 /// Processes a predicate obligation and returns either:
248 /// - `Changed(v)` if the predicate is true, presuming that `v` are also true
249 /// - `Unchanged` if we don't have enough info to be sure
250 /// - `Error(e)` if the predicate does not hold
252 /// This is always inlined, despite its size, because it has a single
253 /// callsite and it is called *very* frequently.
255 fn process_obligation(
257 pending_obligation: &mut Self::Obligation,
258 ) -> ProcessResult<Self::Obligation, Self::Error> {
259 // If we were stalled on some unresolved variables, first check whether
260 // any of them have been resolved; if not, don't bother doing more work
262 let change = match pending_obligation.stalled_on.len() {
263 // Match arms are in order of frequency, which matters because this
264 // code is so hot. 1 and 0 dominate; 2+ is fairly rare.
266 let ty = pending_obligation.stalled_on[0];
267 ShallowResolver::new(self.selcx.infcx()).shallow_resolve_changed(ty)
270 // In this case we haven't changed, but wish to make a change.
274 // This `for` loop was once a call to `all()`, but this lower-level
275 // form was a perf win. See #64545 for details.
277 for &ty in &pending_obligation.stalled_on {
278 if ShallowResolver::new(self.selcx.infcx()).shallow_resolve_changed(ty) {
288 debug!("process_predicate: pending obligation {:?} still stalled on {:?}",
290 .resolve_vars_if_possible(&pending_obligation.obligation),
291 pending_obligation.stalled_on);
292 return ProcessResult::Unchanged;
295 // This part of the code is much colder.
297 pending_obligation.stalled_on.truncate(0);
299 let obligation = &mut pending_obligation.obligation;
301 if obligation.predicate.has_infer_types() {
302 obligation.predicate =
303 self.selcx.infcx().resolve_vars_if_possible(&obligation.predicate);
306 debug!("process_obligation: obligation = {:?} cause = {:?}", obligation, obligation.cause);
308 match obligation.predicate {
309 ty::Predicate::Trait(ref data) => {
310 let trait_obligation = obligation.with(data.clone());
312 if data.is_global() {
313 // no type variables present, can use evaluation for better caching.
314 // FIXME: consider caching errors too.
315 if self.selcx.infcx().predicate_must_hold_considering_regions(&obligation) {
316 debug!("selecting trait `{:?}` at depth {} evaluated to holds",
317 data, obligation.recursion_depth);
318 return ProcessResult::Changed(vec![])
322 match self.selcx.select(&trait_obligation) {
323 Ok(Some(vtable)) => {
324 debug!("selecting trait `{:?}` at depth {} yielded Ok(Some)",
325 data, obligation.recursion_depth);
326 ProcessResult::Changed(mk_pending(vtable.nested_obligations()))
329 debug!("selecting trait `{:?}` at depth {} yielded Ok(None)",
330 data, obligation.recursion_depth);
332 // This is a bit subtle: for the most part, the
333 // only reason we can fail to make progress on
334 // trait selection is because we don't have enough
335 // information about the types in the trait. One
336 // exception is that we sometimes haven't decided
337 // what kind of closure a closure is. *But*, in
338 // that case, it turns out, the type of the
339 // closure will also change, because the closure
340 // also includes references to its upvars as part
341 // of its type, and those types are resolved at
344 // FIXME(#32286) logic seems false if no upvars
345 pending_obligation.stalled_on =
346 trait_ref_type_vars(self.selcx, data.to_poly_trait_ref());
348 debug!("process_predicate: pending obligation {:?} now stalled on {:?}",
349 self.selcx.infcx().resolve_vars_if_possible(obligation),
350 pending_obligation.stalled_on);
352 ProcessResult::Unchanged
354 Err(selection_err) => {
355 info!("selecting trait `{:?}` at depth {} yielded Err",
356 data, obligation.recursion_depth);
358 ProcessResult::Error(CodeSelectionError(selection_err))
363 ty::Predicate::RegionOutlives(ref binder) => {
364 match self.selcx.infcx().region_outlives_predicate(&obligation.cause, binder) {
365 Ok(()) => ProcessResult::Changed(vec![]),
366 Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)),
370 ty::Predicate::TypeOutlives(ref binder) => {
371 // Check if there are higher-ranked vars.
372 match binder.no_bound_vars() {
373 // If there are, inspect the underlying type further.
375 // Convert from `Binder<OutlivesPredicate<Ty, Region>>` to `Binder<Ty>`.
376 let binder = binder.map_bound_ref(|pred| pred.0);
378 // Check if the type has any bound vars.
379 match binder.no_bound_vars() {
380 // If so, this obligation is an error (for now). Eventually we should be
381 // able to support additional cases here, like `for<'a> &'a str: 'a`.
382 // NOTE: this is duplicate-implemented between here and fulfillment.
384 ProcessResult::Error(CodeSelectionError(Unimplemented))
386 // Otherwise, we have something of the form
387 // `for<'a> T: 'a where 'a not in T`, which we can treat as
390 let r_static = self.selcx.tcx().lifetimes.re_static;
391 if self.register_region_obligations {
392 self.selcx.infcx().register_region_obligation_with_cause(
398 ProcessResult::Changed(vec![])
402 // If there aren't, register the obligation.
403 Some(ty::OutlivesPredicate(t_a, r_b)) => {
404 if self.register_region_obligations {
405 self.selcx.infcx().register_region_obligation_with_cause(
411 ProcessResult::Changed(vec![])
416 ty::Predicate::Projection(ref data) => {
417 let project_obligation = obligation.with(data.clone());
418 match project::poly_project_and_unify_type(self.selcx, &project_obligation) {
420 let tcx = self.selcx.tcx();
421 pending_obligation.stalled_on =
422 trait_ref_type_vars(self.selcx, data.to_poly_trait_ref(tcx));
423 ProcessResult::Unchanged
425 Ok(Some(os)) => ProcessResult::Changed(mk_pending(os)),
426 Err(e) => ProcessResult::Error(CodeProjectionError(e))
430 ty::Predicate::ObjectSafe(trait_def_id) => {
431 if !self.selcx.tcx().is_object_safe(trait_def_id) {
432 ProcessResult::Error(CodeSelectionError(Unimplemented))
434 ProcessResult::Changed(vec![])
438 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
439 match self.selcx.infcx().closure_kind(closure_def_id, closure_substs) {
440 Some(closure_kind) => {
441 if closure_kind.extends(kind) {
442 ProcessResult::Changed(vec![])
444 ProcessResult::Error(CodeSelectionError(Unimplemented))
448 ProcessResult::Unchanged
453 ty::Predicate::WellFormed(ty) => {
454 match ty::wf::obligations(
456 obligation.param_env,
457 obligation.cause.body_id,
459 obligation.cause.span,
462 pending_obligation.stalled_on = vec![ty];
463 ProcessResult::Unchanged
465 Some(os) => ProcessResult::Changed(mk_pending(os))
469 ty::Predicate::Subtype(ref subtype) => {
470 match self.selcx.infcx().subtype_predicate(&obligation.cause,
471 obligation.param_env,
474 // None means that both are unresolved.
475 pending_obligation.stalled_on = vec![subtype.skip_binder().a,
476 subtype.skip_binder().b];
477 ProcessResult::Unchanged
480 ProcessResult::Changed(mk_pending(ok.obligations))
483 let expected_found = ExpectedFound::new(subtype.skip_binder().a_is_expected,
484 subtype.skip_binder().a,
485 subtype.skip_binder().b);
486 ProcessResult::Error(
487 FulfillmentErrorCode::CodeSubtypeError(expected_found, err))
492 ty::Predicate::ConstEvaluatable(def_id, substs) => {
493 if obligation.param_env.has_local_value() {
494 ProcessResult::Unchanged
496 if !substs.has_local_value() {
497 let instance = ty::Instance::resolve(
499 obligation.param_env,
503 if let Some(instance) = instance {
508 match self.selcx.tcx().at(obligation.cause.span)
509 .const_eval(obligation.param_env.and(cid)) {
510 Ok(_) => ProcessResult::Changed(vec![]),
511 Err(err) => ProcessResult::Error(
512 CodeSelectionError(ConstEvalFailure(err)))
515 ProcessResult::Error(CodeSelectionError(
516 ConstEvalFailure(ErrorHandled::TooGeneric)
520 pending_obligation.stalled_on = substs.types().collect();
521 ProcessResult::Unchanged
528 fn process_backedge<'c, I>(&mut self, cycle: I,
529 _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>)
530 where I: Clone + Iterator<Item=&'c PendingPredicateObligation<'tcx>>,
532 if self.selcx.coinductive_match(cycle.clone().map(|s| s.obligation.predicate)) {
533 debug!("process_child_obligations: coinductive match");
535 let cycle: Vec<_> = cycle.map(|c| c.obligation.clone()).collect();
536 self.selcx.infcx().report_overflow_error_cycle(&cycle);
541 /// Returns the set of type variables contained in a trait ref
542 fn trait_ref_type_vars<'a, 'tcx>(
543 selcx: &mut SelectionContext<'a, 'tcx>,
544 t: ty::PolyTraitRef<'tcx>,
546 t.skip_binder() // ok b/c this check doesn't care about regions
548 .map(|t| selcx.infcx().resolve_vars_if_possible(&t))
549 .filter(|t| t.has_infer_types())
550 .flat_map(|t| t.walk())
551 .filter(|t| match t.kind { ty::Infer(_) => true, _ => false })
555 fn to_fulfillment_error<'tcx>(
556 error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>)
557 -> FulfillmentError<'tcx>
559 let obligation = error.backtrace.into_iter().next().unwrap().obligation;
560 FulfillmentError::new(obligation, error.error)