1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use mir::interpret::{GlobalId, ErrorHandled};
13 use ty::{self, Ty, TypeFoldable, ToPolyTraitRef, ToPredicate};
14 use ty::error::ExpectedFound;
15 use rustc_data_structures::obligation_forest::{Error, ForestObligation, ObligationForest};
16 use rustc_data_structures::obligation_forest::{ObligationProcessor, ProcessResult};
17 use std::marker::PhantomData;
18 use hir::def_id::DefId;
20 use super::CodeAmbiguity;
21 use super::CodeProjectionError;
22 use super::CodeSelectionError;
23 use super::engine::{TraitEngine, TraitEngineExt};
24 use super::{FulfillmentError, FulfillmentErrorCode};
25 use super::{ObligationCause, PredicateObligation, Obligation};
27 use super::select::SelectionContext;
28 use super::{Unimplemented, ConstEvalFailure};
30 impl<'tcx> ForestObligation for PendingPredicateObligation<'tcx> {
31 type Predicate = ty::Predicate<'tcx>;
33 fn as_predicate(&self) -> &Self::Predicate { &self.obligation.predicate }
36 /// The fulfillment context is used to drive trait resolution. It
37 /// consists of a list of obligations that must be (eventually)
38 /// satisfied. The job is to track which are satisfied, which yielded
39 /// errors, and which are still pending. At any point, users can call
40 /// `select_where_possible`, and the fulfillment context will try to do
41 /// selection, retaining only those obligations that remain
42 /// ambiguous. This may be helpful in pushing type inference
43 /// along. Once all type inference constraints have been generated, the
44 /// method `select_all_or_error` can be used to report any remaining
45 /// ambiguous cases as errors.
46 pub struct FulfillmentContext<'tcx> {
47 // A list of all obligations that have been registered with this
48 // fulfillment context.
49 predicates: ObligationForest<PendingPredicateObligation<'tcx>>,
50 // Should this fulfillment context register type-lives-for-region
51 // obligations on its parent infcx? In some cases, region
52 // obligations are either already known to hold (normalization) or
53 // hopefully verifed elsewhere (type-impls-bound), and therefore
54 // should not be checked.
56 // Note that if we are normalizing a type that we already
57 // know is well-formed, there should be no harm setting this
58 // to true - all the region variables should be determinable
59 // using the RFC 447 rules, which don't depend on
60 // type-lives-for-region constraints, and because the type
61 // is well-formed, the constraints should hold.
62 register_region_obligations: 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
80 pub fn new_ignoring_regions() -> FulfillmentContext<'tcx> {
82 predicates: ObligationForest::new(),
83 register_region_obligations: false
87 /// Attempts to select obligations using `selcx`.
88 fn select(&mut self, selcx: &mut SelectionContext<'a, 'gcx, 'tcx>)
89 -> Result<(), Vec<FulfillmentError<'tcx>>> {
90 debug!("select(obligation-forest-size={})", self.predicates.len());
92 let mut errors = Vec::new();
95 debug!("select: starting another iteration");
97 // Process pending obligations.
98 let outcome = self.predicates.process_obligations(&mut FulfillProcessor {
100 register_region_obligations: self.register_region_obligations
102 debug!("select: outcome={:#?}", outcome);
104 // FIXME: if we kept the original cache key, we could mark projection
105 // obligations as complete for the projection cache here.
108 outcome.errors.into_iter()
109 .map(|e| to_fulfillment_error(e)));
111 // If nothing new was added, no need to keep looping.
117 debug!("select({} predicates remaining, {} errors) done",
118 self.predicates.len(), errors.len());
120 if errors.is_empty() {
128 impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> {
129 /// "Normalize" a projection type `<SomeType as SomeTrait>::X` by
130 /// creating a fresh type variable `$0` as well as a projection
131 /// predicate `<SomeType as SomeTrait>::X == $0`. When the
132 /// inference engine runs, it will attempt to find an impl of
133 /// `SomeTrait` or a where clause that lets us unify `$0` with
134 /// something concrete. If this fails, we'll unify `$0` with
135 /// `projection_ty` again.
136 fn normalize_projection_type<'a, 'gcx>(&mut self,
137 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
138 param_env: ty::ParamEnv<'tcx>,
139 projection_ty: ty::ProjectionTy<'tcx>,
140 cause: ObligationCause<'tcx>)
143 debug!("normalize_projection_type(projection_ty={:?})",
146 debug_assert!(!projection_ty.has_escaping_regions());
148 // FIXME(#20304) -- cache
150 let mut selcx = SelectionContext::new(infcx);
151 let mut obligations = vec![];
152 let normalized_ty = project::normalize_projection_type(&mut selcx,
158 self.register_predicate_obligations(infcx, obligations);
160 debug!("normalize_projection_type: result={:?}", normalized_ty);
165 /// Requires that `ty` must implement the trait with `def_id` in
166 /// the given environment. This trait must not have any type
167 /// parameters (except for `Self`).
168 fn register_bound<'a, 'gcx>(&mut self,
169 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
170 param_env: ty::ParamEnv<'tcx>,
173 cause: ObligationCause<'tcx>)
175 let trait_ref = ty::TraitRef {
177 substs: infcx.tcx.mk_substs_trait(ty, &[]),
179 self.register_predicate_obligation(infcx, Obligation {
183 predicate: trait_ref.to_predicate()
187 fn register_predicate_obligation<'a, 'gcx>(&mut self,
188 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
189 obligation: PredicateObligation<'tcx>)
191 // this helps to reduce duplicate errors, as well as making
192 // debug output much nicer to read and so on.
193 let obligation = infcx.resolve_type_vars_if_possible(&obligation);
195 debug!("register_predicate_obligation(obligation={:?})", obligation);
197 assert!(!infcx.is_in_snapshot());
199 self.predicates.register_obligation(PendingPredicateObligation {
205 fn select_all_or_error<'a, 'gcx>(&mut self,
206 infcx: &InferCtxt<'a, 'gcx, 'tcx>)
207 -> Result<(),Vec<FulfillmentError<'tcx>>>
209 self.select_where_possible(infcx)?;
212 self.predicates.to_errors(CodeAmbiguity)
214 .map(|e| to_fulfillment_error(e))
216 if errors.is_empty() {
223 fn select_where_possible<'a, 'gcx>(&mut self,
224 infcx: &InferCtxt<'a, 'gcx, 'tcx>)
225 -> Result<(),Vec<FulfillmentError<'tcx>>>
227 let mut selcx = SelectionContext::new(infcx);
228 self.select(&mut selcx)
231 fn pending_obligations(&self) -> Vec<PredicateObligation<'tcx>> {
232 self.predicates.map_pending_obligations(|o| o.obligation.clone())
236 struct FulfillProcessor<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
237 selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
238 register_region_obligations: bool
241 fn mk_pending(os: Vec<PredicateObligation<'tcx>>) -> Vec<PendingPredicateObligation<'tcx>> {
242 os.into_iter().map(|o| PendingPredicateObligation {
248 impl<'a, 'b, 'gcx, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'b, 'gcx, 'tcx> {
249 type Obligation = PendingPredicateObligation<'tcx>;
250 type Error = FulfillmentErrorCode<'tcx>;
252 /// Processes a predicate obligation and returns either:
253 /// - `Changed(v)` if the predicate is true, presuming that `v` are also true
254 /// - `Unchanged` if we don't have enough info to be sure
255 /// - `Error(e)` if the predicate does not hold
257 /// This is always inlined, despite its size, because it has a single
258 /// callsite and it is called *very* frequently.
260 fn process_obligation(&mut self,
261 pending_obligation: &mut Self::Obligation)
262 -> ProcessResult<Self::Obligation, Self::Error>
264 // if we were stalled on some unresolved variables, first check
265 // whether any of them have been resolved; if not, don't bother
266 // doing more work yet
267 if !pending_obligation.stalled_on.is_empty() {
268 if pending_obligation.stalled_on.iter().all(|&ty| {
269 // Use the force-inlined variant of shallow_resolve() because this code is hot.
270 let resolved_ty = self.selcx.infcx().inlined_shallow_resolve(&ty);
271 resolved_ty == ty // nothing changed here
273 debug!("process_predicate: pending obligation {:?} still stalled on {:?}",
275 .resolve_type_vars_if_possible(&pending_obligation.obligation),
276 pending_obligation.stalled_on);
277 return ProcessResult::Unchanged;
279 pending_obligation.stalled_on = vec![];
282 let obligation = &mut pending_obligation.obligation;
284 if obligation.predicate.has_infer_types() {
285 obligation.predicate =
286 self.selcx.infcx().resolve_type_vars_if_possible(&obligation.predicate);
289 match obligation.predicate {
290 ty::Predicate::Trait(ref data) => {
291 let trait_obligation = obligation.with(data.clone());
293 if data.is_global() {
294 // no type variables present, can use evaluation for better caching.
295 // FIXME: consider caching errors too.
296 if self.selcx.infcx().predicate_must_hold(&obligation) {
297 debug!("selecting trait `{:?}` at depth {} evaluated to holds",
298 data, obligation.recursion_depth);
299 return ProcessResult::Changed(vec![])
303 match self.selcx.select(&trait_obligation) {
304 Ok(Some(vtable)) => {
305 debug!("selecting trait `{:?}` at depth {} yielded Ok(Some)",
306 data, obligation.recursion_depth);
307 ProcessResult::Changed(mk_pending(vtable.nested_obligations()))
310 debug!("selecting trait `{:?}` at depth {} yielded Ok(None)",
311 data, obligation.recursion_depth);
313 // This is a bit subtle: for the most part, the
314 // only reason we can fail to make progress on
315 // trait selection is because we don't have enough
316 // information about the types in the trait. One
317 // exception is that we sometimes haven't decided
318 // what kind of closure a closure is. *But*, in
319 // that case, it turns out, the type of the
320 // closure will also change, because the closure
321 // also includes references to its upvars as part
322 // of its type, and those types are resolved at
325 // FIXME(#32286) logic seems false if no upvars
326 pending_obligation.stalled_on =
327 trait_ref_type_vars(self.selcx, data.to_poly_trait_ref());
329 debug!("process_predicate: pending obligation {:?} now stalled on {:?}",
330 self.selcx.infcx().resolve_type_vars_if_possible(obligation),
331 pending_obligation.stalled_on);
333 ProcessResult::Unchanged
335 Err(selection_err) => {
336 info!("selecting trait `{:?}` at depth {} yielded Err",
337 data, obligation.recursion_depth);
339 ProcessResult::Error(CodeSelectionError(selection_err))
344 ty::Predicate::RegionOutlives(ref binder) => {
345 match self.selcx.infcx().region_outlives_predicate(&obligation.cause, binder) {
346 Ok(()) => ProcessResult::Changed(vec![]),
347 Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)),
351 ty::Predicate::TypeOutlives(ref binder) => {
352 // Check if there are higher-ranked regions.
353 match binder.no_late_bound_regions() {
354 // If there are, inspect the underlying type further.
356 // Convert from `Binder<OutlivesPredicate<Ty, Region>>` to `Binder<Ty>`.
357 let binder = binder.map_bound_ref(|pred| pred.0);
359 // Check if the type has any bound regions.
360 match binder.no_late_bound_regions() {
361 // If so, this obligation is an error (for now). Eventually we should be
362 // able to support additional cases here, like `for<'a> &'a str: 'a`.
363 // NOTE: this is duplicate-implemented between here and fulfillment.
365 ProcessResult::Error(CodeSelectionError(Unimplemented))
367 // Otherwise, we have something of the form
368 // `for<'a> T: 'a where 'a not in T`, which we can treat as
371 let r_static = self.selcx.tcx().types.re_static;
372 if self.register_region_obligations {
373 self.selcx.infcx().register_region_obligation_with_cause(
379 ProcessResult::Changed(vec![])
383 // If there aren't, register the obligation.
384 Some(ty::OutlivesPredicate(t_a, r_b)) => {
385 if self.register_region_obligations {
386 self.selcx.infcx().register_region_obligation_with_cause(
392 ProcessResult::Changed(vec![])
397 ty::Predicate::Projection(ref data) => {
398 let project_obligation = obligation.with(data.clone());
399 match project::poly_project_and_unify_type(self.selcx, &project_obligation) {
401 let tcx = self.selcx.tcx();
402 pending_obligation.stalled_on =
403 trait_ref_type_vars(self.selcx, data.to_poly_trait_ref(tcx));
404 ProcessResult::Unchanged
406 Ok(Some(os)) => ProcessResult::Changed(mk_pending(os)),
407 Err(e) => ProcessResult::Error(CodeProjectionError(e))
411 ty::Predicate::ObjectSafe(trait_def_id) => {
412 if !self.selcx.tcx().is_object_safe(trait_def_id) {
413 ProcessResult::Error(CodeSelectionError(Unimplemented))
415 ProcessResult::Changed(vec![])
419 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
420 match self.selcx.infcx().closure_kind(closure_def_id, closure_substs) {
421 Some(closure_kind) => {
422 if closure_kind.extends(kind) {
423 ProcessResult::Changed(vec![])
425 ProcessResult::Error(CodeSelectionError(Unimplemented))
429 ProcessResult::Unchanged
434 ty::Predicate::WellFormed(ty) => {
435 match ty::wf::obligations(self.selcx.infcx(),
436 obligation.param_env,
437 obligation.cause.body_id,
438 ty, obligation.cause.span) {
440 pending_obligation.stalled_on = vec![ty];
441 ProcessResult::Unchanged
443 Some(os) => ProcessResult::Changed(mk_pending(os))
447 ty::Predicate::Subtype(ref subtype) => {
448 match self.selcx.infcx().subtype_predicate(&obligation.cause,
449 obligation.param_env,
452 // None means that both are unresolved.
453 pending_obligation.stalled_on = vec![subtype.skip_binder().a,
454 subtype.skip_binder().b];
455 ProcessResult::Unchanged
458 ProcessResult::Changed(mk_pending(ok.obligations))
461 let expected_found = ExpectedFound::new(subtype.skip_binder().a_is_expected,
462 subtype.skip_binder().a,
463 subtype.skip_binder().b);
464 ProcessResult::Error(
465 FulfillmentErrorCode::CodeSubtypeError(expected_found, err))
470 ty::Predicate::ConstEvaluatable(def_id, substs) => {
471 match self.selcx.tcx().lift_to_global(&obligation.param_env) {
473 ProcessResult::Unchanged
476 match self.selcx.tcx().lift_to_global(&substs) {
478 let instance = ty::Instance::resolve(
479 self.selcx.tcx().global_tcx(),
484 if let Some(instance) = instance {
489 match self.selcx.tcx().at(obligation.cause.span)
490 .const_eval(param_env.and(cid)) {
491 Ok(_) => ProcessResult::Changed(vec![]),
492 Err(err) => ProcessResult::Error(
493 CodeSelectionError(ConstEvalFailure(err)))
496 ProcessResult::Error(CodeSelectionError(
497 ConstEvalFailure(ErrorHandled::TooGeneric)
502 pending_obligation.stalled_on = substs.types().collect();
503 ProcessResult::Unchanged
512 fn process_backedge<'c, I>(&mut self, cycle: I,
513 _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>)
514 where I: Clone + Iterator<Item=&'c PendingPredicateObligation<'tcx>>,
516 if self.selcx.coinductive_match(cycle.clone().map(|s| s.obligation.predicate)) {
517 debug!("process_child_obligations: coinductive match");
519 let cycle: Vec<_> = cycle.map(|c| c.obligation.clone()).collect();
520 self.selcx.infcx().report_overflow_error_cycle(&cycle);
525 /// Return the set of type variables contained in a trait ref
526 fn trait_ref_type_vars<'a, 'gcx, 'tcx>(selcx: &mut SelectionContext<'a, 'gcx, 'tcx>,
527 t: ty::PolyTraitRef<'tcx>) -> Vec<Ty<'tcx>>
529 t.skip_binder() // ok b/c this check doesn't care about regions
531 .map(|t| selcx.infcx().resolve_type_vars_if_possible(&t))
532 .filter(|t| t.has_infer_types())
533 .flat_map(|t| t.walk())
534 .filter(|t| match t.sty { ty::Infer(_) => true, _ => false })
538 fn to_fulfillment_error<'tcx>(
539 error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>)
540 -> FulfillmentError<'tcx>
542 let obligation = error.backtrace.into_iter().next().unwrap().obligation;
543 FulfillmentError::new(obligation, error.error)