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::InferTy>,
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 infer = pending_obligation.stalled_on[0];
267 ShallowResolver::new(self.selcx.infcx()).shallow_resolve_changed(infer)
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 &infer in &pending_obligation.stalled_on {
278 if ShallowResolver::new(self.selcx.infcx()).shallow_resolve_changed(infer) {
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 fn infer_ty(ty: Ty<'tcx>) -> ty::InferTy {
310 ty::Infer(infer) => infer,
315 match obligation.predicate {
316 ty::Predicate::Trait(ref data) => {
317 let trait_obligation = obligation.with(data.clone());
319 if data.is_global() {
320 // no type variables present, can use evaluation for better caching.
321 // FIXME: consider caching errors too.
322 if self.selcx.infcx().predicate_must_hold_considering_regions(&obligation) {
323 debug!("selecting trait `{:?}` at depth {} evaluated to holds",
324 data, obligation.recursion_depth);
325 return ProcessResult::Changed(vec![])
329 match self.selcx.select(&trait_obligation) {
330 Ok(Some(vtable)) => {
331 debug!("selecting trait `{:?}` at depth {} yielded Ok(Some)",
332 data, obligation.recursion_depth);
333 ProcessResult::Changed(mk_pending(vtable.nested_obligations()))
336 debug!("selecting trait `{:?}` at depth {} yielded Ok(None)",
337 data, obligation.recursion_depth);
339 // This is a bit subtle: for the most part, the
340 // only reason we can fail to make progress on
341 // trait selection is because we don't have enough
342 // information about the types in the trait. One
343 // exception is that we sometimes haven't decided
344 // what kind of closure a closure is. *But*, in
345 // that case, it turns out, the type of the
346 // closure will also change, because the closure
347 // also includes references to its upvars as part
348 // of its type, and those types are resolved at
351 // FIXME(#32286) logic seems false if no upvars
352 pending_obligation.stalled_on =
353 trait_ref_type_vars(self.selcx, data.to_poly_trait_ref());
355 debug!("process_predicate: pending obligation {:?} now stalled on {:?}",
356 self.selcx.infcx().resolve_vars_if_possible(obligation),
357 pending_obligation.stalled_on);
359 ProcessResult::Unchanged
361 Err(selection_err) => {
362 info!("selecting trait `{:?}` at depth {} yielded Err",
363 data, obligation.recursion_depth);
365 ProcessResult::Error(CodeSelectionError(selection_err))
370 ty::Predicate::RegionOutlives(ref binder) => {
371 match self.selcx.infcx().region_outlives_predicate(&obligation.cause, binder) {
372 Ok(()) => ProcessResult::Changed(vec![]),
373 Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)),
377 ty::Predicate::TypeOutlives(ref binder) => {
378 // Check if there are higher-ranked vars.
379 match binder.no_bound_vars() {
380 // If there are, inspect the underlying type further.
382 // Convert from `Binder<OutlivesPredicate<Ty, Region>>` to `Binder<Ty>`.
383 let binder = binder.map_bound_ref(|pred| pred.0);
385 // Check if the type has any bound vars.
386 match binder.no_bound_vars() {
387 // If so, this obligation is an error (for now). Eventually we should be
388 // able to support additional cases here, like `for<'a> &'a str: 'a`.
389 // NOTE: this is duplicate-implemented between here and fulfillment.
391 ProcessResult::Error(CodeSelectionError(Unimplemented))
393 // Otherwise, we have something of the form
394 // `for<'a> T: 'a where 'a not in T`, which we can treat as
397 let r_static = self.selcx.tcx().lifetimes.re_static;
398 if self.register_region_obligations {
399 self.selcx.infcx().register_region_obligation_with_cause(
405 ProcessResult::Changed(vec![])
409 // If there aren't, register the obligation.
410 Some(ty::OutlivesPredicate(t_a, r_b)) => {
411 if self.register_region_obligations {
412 self.selcx.infcx().register_region_obligation_with_cause(
418 ProcessResult::Changed(vec![])
423 ty::Predicate::Projection(ref data) => {
424 let project_obligation = obligation.with(data.clone());
425 match project::poly_project_and_unify_type(self.selcx, &project_obligation) {
427 let tcx = self.selcx.tcx();
428 pending_obligation.stalled_on =
429 trait_ref_type_vars(self.selcx, data.to_poly_trait_ref(tcx));
430 ProcessResult::Unchanged
432 Ok(Some(os)) => ProcessResult::Changed(mk_pending(os)),
433 Err(e) => ProcessResult::Error(CodeProjectionError(e))
437 ty::Predicate::ObjectSafe(trait_def_id) => {
438 if !self.selcx.tcx().is_object_safe(trait_def_id) {
439 ProcessResult::Error(CodeSelectionError(Unimplemented))
441 ProcessResult::Changed(vec![])
445 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
446 match self.selcx.infcx().closure_kind(closure_def_id, closure_substs) {
447 Some(closure_kind) => {
448 if closure_kind.extends(kind) {
449 ProcessResult::Changed(vec![])
451 ProcessResult::Error(CodeSelectionError(Unimplemented))
455 ProcessResult::Unchanged
460 ty::Predicate::WellFormed(ty) => {
461 match ty::wf::obligations(
463 obligation.param_env,
464 obligation.cause.body_id,
466 obligation.cause.span,
469 pending_obligation.stalled_on = vec![infer_ty(ty)];
470 ProcessResult::Unchanged
472 Some(os) => ProcessResult::Changed(mk_pending(os))
476 ty::Predicate::Subtype(ref subtype) => {
477 match self.selcx.infcx().subtype_predicate(&obligation.cause,
478 obligation.param_env,
481 // None means that both are unresolved.
482 pending_obligation.stalled_on = vec![infer_ty(subtype.skip_binder().a),
483 infer_ty(subtype.skip_binder().b)];
484 ProcessResult::Unchanged
487 ProcessResult::Changed(mk_pending(ok.obligations))
490 let expected_found = ExpectedFound::new(subtype.skip_binder().a_is_expected,
491 subtype.skip_binder().a,
492 subtype.skip_binder().b);
493 ProcessResult::Error(
494 FulfillmentErrorCode::CodeSubtypeError(expected_found, err))
499 ty::Predicate::ConstEvaluatable(def_id, substs) => {
500 if obligation.param_env.has_local_value() {
501 ProcessResult::Unchanged
503 if !substs.has_local_value() {
504 let instance = ty::Instance::resolve(
506 obligation.param_env,
510 if let Some(instance) = instance {
515 match self.selcx.tcx().at(obligation.cause.span)
516 .const_eval(obligation.param_env.and(cid)) {
517 Ok(_) => ProcessResult::Changed(vec![]),
518 Err(err) => ProcessResult::Error(
519 CodeSelectionError(ConstEvalFailure(err)))
522 ProcessResult::Error(CodeSelectionError(
523 ConstEvalFailure(ErrorHandled::TooGeneric)
527 pending_obligation.stalled_on =
528 substs.types().map(|ty| infer_ty(ty)).collect();
529 ProcessResult::Unchanged
536 fn process_backedge<'c, I>(&mut self, cycle: I,
537 _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>)
538 where I: Clone + Iterator<Item=&'c PendingPredicateObligation<'tcx>>,
540 if self.selcx.coinductive_match(cycle.clone().map(|s| s.obligation.predicate)) {
541 debug!("process_child_obligations: coinductive match");
543 let cycle: Vec<_> = cycle.map(|c| c.obligation.clone()).collect();
544 self.selcx.infcx().report_overflow_error_cycle(&cycle);
549 /// Returns the set of type variables contained in a trait ref
550 fn trait_ref_type_vars<'a, 'tcx>(
551 selcx: &mut SelectionContext<'a, 'tcx>,
552 t: ty::PolyTraitRef<'tcx>,
553 ) -> Vec<ty::InferTy> {
554 t.skip_binder() // ok b/c this check doesn't care about regions
556 .map(|t| selcx.infcx().resolve_vars_if_possible(&t))
557 .filter(|t| t.has_infer_types())
558 .flat_map(|t| t.walk())
559 .filter_map(|t| match t.kind { ty::Infer(infer) => Some(infer), _ => None })
563 fn to_fulfillment_error<'tcx>(
564 error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>)
565 -> FulfillmentError<'tcx>
567 let obligation = error.backtrace.into_iter().next().unwrap().obligation;
568 FulfillmentError::new(obligation, error.error)