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 impl<'a, 'gcx, 'tcx> FulfillmentContext<'tcx> {
72 /// Creates a new fulfillment context.
73 pub fn new() -> FulfillmentContext<'tcx> {
75 predicates: ObligationForest::new(),
76 register_region_obligations: true,
77 usable_in_snapshot: false,
81 pub fn new_in_snapshot() -> FulfillmentContext<'tcx> {
83 predicates: ObligationForest::new(),
84 register_region_obligations: true,
85 usable_in_snapshot: true,
89 pub fn new_ignoring_regions() -> FulfillmentContext<'tcx> {
91 predicates: ObligationForest::new(),
92 register_region_obligations: false,
93 usable_in_snapshot: false
97 /// Attempts to select obligations using `selcx`.
98 fn select(&mut self, selcx: &mut SelectionContext<'a, 'gcx, 'tcx>)
99 -> Result<(), Vec<FulfillmentError<'tcx>>> {
100 debug!("select(obligation-forest-size={})", self.predicates.len());
102 let mut errors = Vec::new();
105 debug!("select: starting another iteration");
107 // Process pending obligations.
108 let outcome = self.predicates.process_obligations(&mut FulfillProcessor {
110 register_region_obligations: self.register_region_obligations
112 debug!("select: outcome={:#?}", outcome);
114 // FIXME: if we kept the original cache key, we could mark projection
115 // obligations as complete for the projection cache here.
118 outcome.errors.into_iter()
119 .map(|e| to_fulfillment_error(e)));
121 // If nothing new was added, no need to keep looping.
127 debug!("select({} predicates remaining, {} errors) done",
128 self.predicates.len(), errors.len());
130 if errors.is_empty() {
138 impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> {
139 /// "Normalize" a projection type `<SomeType as SomeTrait>::X` by
140 /// creating a fresh type variable `$0` as well as a projection
141 /// predicate `<SomeType as SomeTrait>::X == $0`. When the
142 /// inference engine runs, it will attempt to find an impl of
143 /// `SomeTrait` or a where-clause that lets us unify `$0` with
144 /// something concrete. If this fails, we'll unify `$0` with
145 /// `projection_ty` again.
146 fn normalize_projection_type<'a, 'gcx>(&mut self,
147 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
148 param_env: ty::ParamEnv<'tcx>,
149 projection_ty: ty::ProjectionTy<'tcx>,
150 cause: ObligationCause<'tcx>)
153 debug!("normalize_projection_type(projection_ty={:?})",
156 debug_assert!(!projection_ty.has_escaping_bound_vars());
158 // FIXME(#20304) -- cache
160 let mut selcx = SelectionContext::new(infcx);
161 let mut obligations = vec![];
162 let normalized_ty = project::normalize_projection_type(&mut selcx,
168 self.register_predicate_obligations(infcx, obligations);
170 debug!("normalize_projection_type: result={:?}", normalized_ty);
175 fn register_predicate_obligation<'a, 'gcx>(&mut self,
176 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
177 obligation: PredicateObligation<'tcx>)
179 // this helps to reduce duplicate errors, as well as making
180 // debug output much nicer to read and so on.
181 let obligation = infcx.resolve_type_vars_if_possible(&obligation);
183 debug!("register_predicate_obligation(obligation={:?})", obligation);
185 assert!(!infcx.is_in_snapshot() || self.usable_in_snapshot);
187 self.predicates.register_obligation(PendingPredicateObligation {
193 fn select_all_or_error<'a, 'gcx>(
195 infcx: &InferCtxt<'a, 'gcx, 'tcx>
196 ) -> Result<(),Vec<FulfillmentError<'tcx>>>
198 self.select_where_possible(infcx)?;
201 self.predicates.to_errors(CodeAmbiguity)
203 .map(|e| to_fulfillment_error(e))
205 if errors.is_empty() {
212 fn select_where_possible<'a, 'gcx>(&mut self,
213 infcx: &InferCtxt<'a, 'gcx, 'tcx>)
214 -> Result<(),Vec<FulfillmentError<'tcx>>>
216 let mut selcx = SelectionContext::new(infcx);
217 self.select(&mut selcx)
220 fn pending_obligations(&self) -> Vec<PredicateObligation<'tcx>> {
221 self.predicates.map_pending_obligations(|o| o.obligation.clone())
225 struct FulfillProcessor<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
226 selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
227 register_region_obligations: bool
230 fn mk_pending(os: Vec<PredicateObligation<'tcx>>) -> Vec<PendingPredicateObligation<'tcx>> {
231 os.into_iter().map(|o| PendingPredicateObligation {
237 impl<'a, 'b, 'gcx, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'b, 'gcx, 'tcx> {
238 type Obligation = PendingPredicateObligation<'tcx>;
239 type Error = FulfillmentErrorCode<'tcx>;
241 /// Processes a predicate obligation and returns either:
242 /// - `Changed(v)` if the predicate is true, presuming that `v` are also true
243 /// - `Unchanged` if we don't have enough info to be sure
244 /// - `Error(e)` if the predicate does not hold
246 /// This is always inlined, despite its size, because it has a single
247 /// callsite and it is called *very* frequently.
249 fn process_obligation(&mut self,
250 pending_obligation: &mut Self::Obligation)
251 -> ProcessResult<Self::Obligation, Self::Error>
253 // if we were stalled on some unresolved variables, first check
254 // whether any of them have been resolved; if not, don't bother
255 // doing more work yet
256 if !pending_obligation.stalled_on.is_empty() {
257 if pending_obligation.stalled_on.iter().all(|&ty| {
258 // Use the force-inlined variant of shallow_resolve() because this code is hot.
259 let resolved = ShallowResolver::new(self.selcx.infcx()).inlined_shallow_resolve(ty);
260 resolved == ty // nothing changed here
262 debug!("process_predicate: pending obligation {:?} still stalled on {:?}",
264 .resolve_type_vars_if_possible(&pending_obligation.obligation),
265 pending_obligation.stalled_on);
266 return ProcessResult::Unchanged;
268 pending_obligation.stalled_on = vec![];
271 let obligation = &mut pending_obligation.obligation;
273 if obligation.predicate.has_infer_types() {
274 obligation.predicate =
275 self.selcx.infcx().resolve_type_vars_if_possible(&obligation.predicate);
278 debug!("process_obligation: obligation = {:?}", obligation);
280 match obligation.predicate {
281 ty::Predicate::Trait(ref data) => {
282 let trait_obligation = obligation.with(data.clone());
284 if data.is_global() {
285 // no type variables present, can use evaluation for better caching.
286 // FIXME: consider caching errors too.
287 if self.selcx.infcx().predicate_must_hold_considering_regions(&obligation) {
288 debug!("selecting trait `{:?}` at depth {} evaluated to holds",
289 data, obligation.recursion_depth);
290 return ProcessResult::Changed(vec![])
294 match self.selcx.select(&trait_obligation) {
295 Ok(Some(vtable)) => {
296 debug!("selecting trait `{:?}` at depth {} yielded Ok(Some)",
297 data, obligation.recursion_depth);
298 ProcessResult::Changed(mk_pending(vtable.nested_obligations()))
301 debug!("selecting trait `{:?}` at depth {} yielded Ok(None)",
302 data, obligation.recursion_depth);
304 // This is a bit subtle: for the most part, the
305 // only reason we can fail to make progress on
306 // trait selection is because we don't have enough
307 // information about the types in the trait. One
308 // exception is that we sometimes haven't decided
309 // what kind of closure a closure is. *But*, in
310 // that case, it turns out, the type of the
311 // closure will also change, because the closure
312 // also includes references to its upvars as part
313 // of its type, and those types are resolved at
316 // FIXME(#32286) logic seems false if no upvars
317 pending_obligation.stalled_on =
318 trait_ref_type_vars(self.selcx, data.to_poly_trait_ref());
320 debug!("process_predicate: pending obligation {:?} now stalled on {:?}",
321 self.selcx.infcx().resolve_type_vars_if_possible(obligation),
322 pending_obligation.stalled_on);
324 ProcessResult::Unchanged
326 Err(selection_err) => {
327 info!("selecting trait `{:?}` at depth {} yielded Err",
328 data, obligation.recursion_depth);
330 ProcessResult::Error(CodeSelectionError(selection_err))
335 ty::Predicate::RegionOutlives(ref binder) => {
336 match self.selcx.infcx().region_outlives_predicate(&obligation.cause, binder) {
337 Ok(()) => ProcessResult::Changed(vec![]),
338 Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)),
342 ty::Predicate::TypeOutlives(ref binder) => {
343 // Check if there are higher-ranked vars.
344 match binder.no_bound_vars() {
345 // If there are, inspect the underlying type further.
347 // Convert from `Binder<OutlivesPredicate<Ty, Region>>` to `Binder<Ty>`.
348 let binder = binder.map_bound_ref(|pred| pred.0);
350 // Check if the type has any bound vars.
351 match binder.no_bound_vars() {
352 // If so, this obligation is an error (for now). Eventually we should be
353 // able to support additional cases here, like `for<'a> &'a str: 'a`.
354 // NOTE: this is duplicate-implemented between here and fulfillment.
356 ProcessResult::Error(CodeSelectionError(Unimplemented))
358 // Otherwise, we have something of the form
359 // `for<'a> T: 'a where 'a not in T`, which we can treat as
362 let r_static = self.selcx.tcx().lifetimes.re_static;
363 if self.register_region_obligations {
364 self.selcx.infcx().register_region_obligation_with_cause(
370 ProcessResult::Changed(vec![])
374 // If there aren't, register the obligation.
375 Some(ty::OutlivesPredicate(t_a, r_b)) => {
376 if self.register_region_obligations {
377 self.selcx.infcx().register_region_obligation_with_cause(
383 ProcessResult::Changed(vec![])
388 ty::Predicate::Projection(ref data) => {
389 let project_obligation = obligation.with(data.clone());
390 match project::poly_project_and_unify_type(self.selcx, &project_obligation) {
392 let tcx = self.selcx.tcx();
393 pending_obligation.stalled_on =
394 trait_ref_type_vars(self.selcx, data.to_poly_trait_ref(tcx));
395 ProcessResult::Unchanged
397 Ok(Some(os)) => ProcessResult::Changed(mk_pending(os)),
398 Err(e) => ProcessResult::Error(CodeProjectionError(e))
402 ty::Predicate::ObjectSafe(trait_def_id) => {
403 if !self.selcx.tcx().is_object_safe(trait_def_id) {
404 ProcessResult::Error(CodeSelectionError(Unimplemented))
406 ProcessResult::Changed(vec![])
410 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
411 match self.selcx.infcx().closure_kind(closure_def_id, closure_substs) {
412 Some(closure_kind) => {
413 if closure_kind.extends(kind) {
414 ProcessResult::Changed(vec![])
416 ProcessResult::Error(CodeSelectionError(Unimplemented))
420 ProcessResult::Unchanged
425 ty::Predicate::WellFormed(ty) => {
426 match ty::wf::obligations(self.selcx.infcx(),
427 obligation.param_env,
428 obligation.cause.body_id,
429 ty, obligation.cause.span) {
431 pending_obligation.stalled_on = vec![ty];
432 ProcessResult::Unchanged
434 Some(os) => ProcessResult::Changed(mk_pending(os))
438 ty::Predicate::Subtype(ref subtype) => {
439 match self.selcx.infcx().subtype_predicate(&obligation.cause,
440 obligation.param_env,
443 // None means that both are unresolved.
444 pending_obligation.stalled_on = vec![subtype.skip_binder().a,
445 subtype.skip_binder().b];
446 ProcessResult::Unchanged
449 ProcessResult::Changed(mk_pending(ok.obligations))
452 let expected_found = ExpectedFound::new(subtype.skip_binder().a_is_expected,
453 subtype.skip_binder().a,
454 subtype.skip_binder().b);
455 ProcessResult::Error(
456 FulfillmentErrorCode::CodeSubtypeError(expected_found, err))
461 ty::Predicate::ConstEvaluatable(def_id, substs) => {
462 match self.selcx.tcx().lift_to_global(&obligation.param_env) {
464 ProcessResult::Unchanged
467 match self.selcx.tcx().lift_to_global(&substs) {
469 let instance = ty::Instance::resolve(
470 self.selcx.tcx().global_tcx(),
475 if let Some(instance) = instance {
480 match self.selcx.tcx().at(obligation.cause.span)
481 .const_eval(param_env.and(cid)) {
482 Ok(_) => ProcessResult::Changed(vec![]),
483 Err(err) => ProcessResult::Error(
484 CodeSelectionError(ConstEvalFailure(err)))
487 ProcessResult::Error(CodeSelectionError(
488 ConstEvalFailure(ErrorHandled::TooGeneric)
493 pending_obligation.stalled_on = substs.types().collect();
494 ProcessResult::Unchanged
503 fn process_backedge<'c, I>(&mut self, cycle: I,
504 _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>)
505 where I: Clone + Iterator<Item=&'c PendingPredicateObligation<'tcx>>,
507 if self.selcx.coinductive_match(cycle.clone().map(|s| s.obligation.predicate)) {
508 debug!("process_child_obligations: coinductive match");
510 let cycle: Vec<_> = cycle.map(|c| c.obligation.clone()).collect();
511 self.selcx.infcx().report_overflow_error_cycle(&cycle);
516 /// Returns the set of type variables contained in a trait ref
517 fn trait_ref_type_vars<'a, 'gcx, 'tcx>(selcx: &mut SelectionContext<'a, 'gcx, 'tcx>,
518 t: ty::PolyTraitRef<'tcx>) -> Vec<Ty<'tcx>>
520 t.skip_binder() // ok b/c this check doesn't care about regions
522 .map(|t| selcx.infcx().resolve_type_vars_if_possible(&t))
523 .filter(|t| t.has_infer_types())
524 .flat_map(|t| t.walk())
525 .filter(|t| match t.sty { ty::Infer(_) => true, _ => false })
529 fn to_fulfillment_error<'tcx>(
530 error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>)
531 -> FulfillmentError<'tcx>
533 let obligation = error.backtrace.into_iter().next().unwrap().obligation;
534 FulfillmentError::new(obligation, error.error)