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.
11 use infer::{RegionObligation, InferCtxt};
12 use ty::{self, Ty, TypeFoldable, ToPolyTraitRef, ToPredicate};
13 use ty::error::ExpectedFound;
14 use rustc_data_structures::obligation_forest::{ObligationForest, Error};
15 use rustc_data_structures::obligation_forest::{ForestObligation, ObligationProcessor};
16 use std::marker::PhantomData;
17 use hir::def_id::DefId;
19 use super::CodeAmbiguity;
20 use super::CodeProjectionError;
21 use super::CodeSelectionError;
22 use super::{FulfillmentError, FulfillmentErrorCode};
23 use super::{ObligationCause, PredicateObligation, Obligation};
25 use super::select::SelectionContext;
26 use super::{Unimplemented, ConstEvalFailure};
28 impl<'tcx> ForestObligation for PendingPredicateObligation<'tcx> {
29 type Predicate = ty::Predicate<'tcx>;
31 fn as_predicate(&self) -> &Self::Predicate { &self.obligation.predicate }
34 /// The fulfillment context is used to drive trait resolution. It
35 /// consists of a list of obligations that must be (eventually)
36 /// satisfied. The job is to track which are satisfied, which yielded
37 /// errors, and which are still pending. At any point, users can call
38 /// `select_where_possible`, and the fulfillment context will try to do
39 /// selection, retaining only those obligations that remain
40 /// ambiguous. This may be helpful in pushing type inference
41 /// along. Once all type inference constraints have been generated, the
42 /// method `select_all_or_error` can be used to report any remaining
43 /// ambiguous cases as errors.
45 pub struct FulfillmentContext<'tcx> {
46 // A list of all obligations that have been registered with this
47 // fulfillment context.
48 predicates: ObligationForest<PendingPredicateObligation<'tcx>>,
49 // Should this fulfillment context register type-lives-for-region
50 // obligations on its parent infcx? In some cases, region
51 // obligations are either already known to hold (normalization) or
52 // hopefully verifed elsewhere (type-impls-bound), and therefore
53 // should not be checked.
55 // Note that if we are normalizing a type that we already
56 // know is well-formed, there should be no harm setting this
57 // to true - all the region variables should be determinable
58 // using the RFC 447 rules, which don't depend on
59 // type-lives-for-region constraints, and because the type
60 // is well-formed, the constraints should hold.
61 register_region_obligations: bool,
64 #[derive(Clone, Debug)]
65 pub struct PendingPredicateObligation<'tcx> {
66 pub obligation: PredicateObligation<'tcx>,
67 pub stalled_on: Vec<Ty<'tcx>>,
70 impl<'a, 'gcx, 'tcx> FulfillmentContext<'tcx> {
71 /// Creates a new fulfillment context.
72 pub fn new() -> FulfillmentContext<'tcx> {
74 predicates: ObligationForest::new(),
75 register_region_obligations: true
79 pub fn new_ignoring_regions() -> FulfillmentContext<'tcx> {
81 predicates: ObligationForest::new(),
82 register_region_obligations: false
86 /// "Normalize" a projection type `<SomeType as SomeTrait>::X` by
87 /// creating a fresh type variable `$0` as well as a projection
88 /// predicate `<SomeType as SomeTrait>::X == $0`. When the
89 /// inference engine runs, it will attempt to find an impl of
90 /// `SomeTrait` or a where clause that lets us unify `$0` with
91 /// something concrete. If this fails, we'll unify `$0` with
92 /// `projection_ty` again.
93 pub fn normalize_projection_type(&mut self,
94 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
95 param_env: ty::ParamEnv<'tcx>,
96 projection_ty: ty::ProjectionTy<'tcx>,
97 cause: ObligationCause<'tcx>)
100 debug!("normalize_projection_type(projection_ty={:?})",
103 assert!(!projection_ty.has_escaping_regions());
105 // FIXME(#20304) -- cache
107 let mut selcx = SelectionContext::new(infcx);
108 let normalized = project::normalize_projection_type(&mut selcx,
114 for obligation in normalized.obligations {
115 self.register_predicate_obligation(infcx, obligation);
118 debug!("normalize_projection_type: result={:?}", normalized.value);
123 /// Requires that `ty` must implement the trait with `def_id` in
124 /// the given environment. This trait must not have any type
125 /// parameters (except for `Self`).
126 pub fn register_bound(&mut self,
127 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
128 param_env: ty::ParamEnv<'tcx>,
131 cause: ObligationCause<'tcx>)
133 let trait_ref = ty::TraitRef {
135 substs: infcx.tcx.mk_substs_trait(ty, &[]),
137 self.register_predicate_obligation(infcx, Obligation {
141 predicate: trait_ref.to_predicate()
145 pub fn register_predicate_obligation(&mut self,
146 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
147 obligation: PredicateObligation<'tcx>)
149 // this helps to reduce duplicate errors, as well as making
150 // debug output much nicer to read and so on.
151 let obligation = infcx.resolve_type_vars_if_possible(&obligation);
153 debug!("register_predicate_obligation(obligation={:?})", obligation);
155 assert!(!infcx.is_in_snapshot());
157 self.predicates.register_obligation(PendingPredicateObligation {
163 pub fn register_predicate_obligations<I>(&mut self,
164 infcx: &InferCtxt<'a, 'gcx, 'tcx>,
166 where I: IntoIterator<Item = PredicateObligation<'tcx>>
168 for obligation in obligations {
169 self.register_predicate_obligation(infcx, obligation);
173 pub fn select_all_or_error(&mut self,
174 infcx: &InferCtxt<'a, 'gcx, 'tcx>)
175 -> Result<(),Vec<FulfillmentError<'tcx>>>
177 self.select_where_possible(infcx)?;
180 self.predicates.to_errors(CodeAmbiguity)
182 .map(|e| to_fulfillment_error(e))
184 if errors.is_empty() {
191 pub fn select_where_possible(&mut self,
192 infcx: &InferCtxt<'a, 'gcx, 'tcx>)
193 -> Result<(),Vec<FulfillmentError<'tcx>>>
195 let mut selcx = SelectionContext::new(infcx);
196 self.select(&mut selcx)
199 pub fn pending_obligations(&self) -> Vec<PendingPredicateObligation<'tcx>> {
200 self.predicates.pending_obligations()
203 /// Attempts to select obligations using `selcx`. If `only_new_obligations` is true, then it
204 /// only attempts to select obligations that haven't been seen before.
205 fn select(&mut self, selcx: &mut SelectionContext<'a, 'gcx, 'tcx>)
206 -> Result<(),Vec<FulfillmentError<'tcx>>> {
207 debug!("select(obligation-forest-size={})", self.predicates.len());
209 let mut errors = Vec::new();
212 debug!("select: starting another iteration");
214 // Process pending obligations.
215 let outcome = self.predicates.process_obligations(&mut FulfillProcessor {
217 register_region_obligations: self.register_region_obligations
219 debug!("select: outcome={:?}", outcome);
221 // FIXME: if we kept the original cache key, we could mark projection
222 // obligations as complete for the projection cache here.
225 outcome.errors.into_iter()
226 .map(|e| to_fulfillment_error(e)));
228 // If nothing new was added, no need to keep looping.
234 debug!("select({} predicates remaining, {} errors) done",
235 self.predicates.len(), errors.len());
237 if errors.is_empty() {
245 struct FulfillProcessor<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
246 selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>,
247 register_region_obligations: bool
250 impl<'a, 'b, 'gcx, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'b, 'gcx, 'tcx> {
251 type Obligation = PendingPredicateObligation<'tcx>;
252 type Error = FulfillmentErrorCode<'tcx>;
254 fn process_obligation(&mut self,
255 obligation: &mut Self::Obligation)
256 -> Result<Option<Vec<Self::Obligation>>, Self::Error>
258 process_predicate(self.selcx, obligation, self.register_region_obligations)
259 .map(|os| os.map(|os| os.into_iter().map(|o| PendingPredicateObligation {
265 fn process_backedge<'c, I>(&mut self, cycle: I,
266 _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>)
267 where I: Clone + Iterator<Item=&'c PendingPredicateObligation<'tcx>>,
269 if self.selcx.coinductive_match(cycle.clone().map(|s| s.obligation.predicate)) {
270 debug!("process_child_obligations: coinductive match");
272 let cycle : Vec<_> = cycle.map(|c| c.obligation.clone()).collect();
273 self.selcx.infcx().report_overflow_error_cycle(&cycle);
278 /// Return the set of type variables contained in a trait ref
279 fn trait_ref_type_vars<'a, 'gcx, 'tcx>(selcx: &mut SelectionContext<'a, 'gcx, 'tcx>,
280 t: ty::PolyTraitRef<'tcx>) -> Vec<Ty<'tcx>>
282 t.skip_binder() // ok b/c this check doesn't care about regions
284 .map(|t| selcx.infcx().resolve_type_vars_if_possible(&t))
285 .filter(|t| t.has_infer_types())
286 .flat_map(|t| t.walk())
287 .filter(|t| match t.sty { ty::TyInfer(_) => true, _ => false })
291 /// Processes a predicate obligation and returns either:
292 /// - `Ok(Some(v))` if the predicate is true, presuming that `v` are also true
293 /// - `Ok(None)` if we don't have enough info to be sure
294 /// - `Err` if the predicate does not hold
295 fn process_predicate<'a, 'gcx, 'tcx>(
296 selcx: &mut SelectionContext<'a, 'gcx, 'tcx>,
297 pending_obligation: &mut PendingPredicateObligation<'tcx>,
298 register_region_obligations: bool)
299 -> Result<Option<Vec<PredicateObligation<'tcx>>>,
300 FulfillmentErrorCode<'tcx>>
302 // if we were stalled on some unresolved variables, first check
303 // whether any of them have been resolved; if not, don't bother
304 // doing more work yet
305 if !pending_obligation.stalled_on.is_empty() {
306 if pending_obligation.stalled_on.iter().all(|&ty| {
307 let resolved_ty = selcx.infcx().shallow_resolve(&ty);
308 resolved_ty == ty // nothing changed here
310 debug!("process_predicate: pending obligation {:?} still stalled on {:?}",
311 selcx.infcx().resolve_type_vars_if_possible(&pending_obligation.obligation),
312 pending_obligation.stalled_on);
315 pending_obligation.stalled_on = vec![];
318 let obligation = &mut pending_obligation.obligation;
320 if obligation.predicate.has_infer_types() {
321 obligation.predicate = selcx.infcx().resolve_type_vars_if_possible(&obligation.predicate);
324 match obligation.predicate {
325 ty::Predicate::Trait(ref data) => {
326 let trait_obligation = obligation.with(data.clone());
328 if data.is_global() {
329 // no type variables present, can use evaluation for better caching.
330 // FIXME: consider caching errors too.
332 // make defaulted unit go through the slow path for better warnings,
333 // please remove this when the warnings are removed.
334 !trait_obligation.predicate.skip_binder().self_ty().is_defaulted_unit() &&
335 selcx.evaluate_obligation_conservatively(&obligation) {
336 debug!("selecting trait `{:?}` at depth {} evaluated to holds",
337 data, obligation.recursion_depth);
338 return Ok(Some(vec![]))
342 match selcx.select(&trait_obligation) {
343 Ok(Some(vtable)) => {
344 debug!("selecting trait `{:?}` at depth {} yielded Ok(Some)",
345 data, obligation.recursion_depth);
346 Ok(Some(vtable.nested_obligations()))
349 debug!("selecting trait `{:?}` at depth {} yielded Ok(None)",
350 data, obligation.recursion_depth);
352 // This is a bit subtle: for the most part, the
353 // only reason we can fail to make progress on
354 // trait selection is because we don't have enough
355 // information about the types in the trait. One
356 // exception is that we sometimes haven't decided
357 // what kind of closure a closure is. *But*, in
358 // that case, it turns out, the type of the
359 // closure will also change, because the closure
360 // also includes references to its upvars as part
361 // of its type, and those types are resolved at
364 // FIXME(#32286) logic seems false if no upvars
365 pending_obligation.stalled_on =
366 trait_ref_type_vars(selcx, data.to_poly_trait_ref());
368 debug!("process_predicate: pending obligation {:?} now stalled on {:?}",
369 selcx.infcx().resolve_type_vars_if_possible(obligation),
370 pending_obligation.stalled_on);
374 Err(selection_err) => {
375 info!("selecting trait `{:?}` at depth {} yielded Err",
376 data, obligation.recursion_depth);
378 Err(CodeSelectionError(selection_err))
383 ty::Predicate::RegionOutlives(ref binder) => {
384 match selcx.infcx().region_outlives_predicate(&obligation.cause, binder) {
385 Ok(()) => Ok(Some(Vec::new())),
386 Err(_) => Err(CodeSelectionError(Unimplemented)),
390 ty::Predicate::TypeOutlives(ref binder) => {
391 // Check if there are higher-ranked regions.
392 match binder.no_late_bound_regions() {
393 // If there are, inspect the underlying type further.
395 // Convert from `Binder<OutlivesPredicate<Ty, Region>>` to `Binder<Ty>`.
396 let binder = binder.map_bound_ref(|pred| pred.0);
398 // Check if the type has any bound regions.
399 match binder.no_late_bound_regions() {
400 // If so, this obligation is an error (for now). Eventually we should be
401 // able to support additional cases here, like `for<'a> &'a str: 'a`.
403 Err(CodeSelectionError(Unimplemented))
405 // Otherwise, we have something of the form
406 // `for<'a> T: 'a where 'a not in T`, which we can treat as `T: 'static`.
408 let r_static = selcx.tcx().types.re_static;
409 if register_region_obligations {
410 selcx.infcx().register_region_obligation(
411 obligation.cause.body_id,
414 sub_region: r_static,
415 cause: obligation.cause.clone(),
422 // If there aren't, register the obligation.
423 Some(ty::OutlivesPredicate(t_a, r_b)) => {
424 if register_region_obligations {
425 selcx.infcx().register_region_obligation(
426 obligation.cause.body_id,
430 cause: obligation.cause.clone()
438 ty::Predicate::Projection(ref data) => {
439 let project_obligation = obligation.with(data.clone());
440 match project::poly_project_and_unify_type(selcx, &project_obligation) {
442 let tcx = selcx.tcx();
443 pending_obligation.stalled_on =
444 trait_ref_type_vars(selcx, data.to_poly_trait_ref(tcx));
448 Err(e) => Err(CodeProjectionError(e))
452 ty::Predicate::ObjectSafe(trait_def_id) => {
453 if !selcx.tcx().is_object_safe(trait_def_id) {
454 Err(CodeSelectionError(Unimplemented))
460 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
461 match selcx.infcx().closure_kind(closure_def_id, closure_substs) {
462 Some(closure_kind) => {
463 if closure_kind.extends(kind) {
466 Err(CodeSelectionError(Unimplemented))
475 ty::Predicate::WellFormed(ty) => {
476 match ty::wf::obligations(selcx.infcx(),
477 obligation.param_env,
478 obligation.cause.body_id,
479 ty, obligation.cause.span) {
481 pending_obligation.stalled_on = vec![ty];
488 ty::Predicate::Subtype(ref subtype) => {
489 match selcx.infcx().subtype_predicate(&obligation.cause,
490 obligation.param_env,
493 // none means that both are unresolved
494 pending_obligation.stalled_on = vec![subtype.skip_binder().a,
495 subtype.skip_binder().b];
499 Ok(Some(ok.obligations))
502 let expected_found = ExpectedFound::new(subtype.skip_binder().a_is_expected,
503 subtype.skip_binder().a,
504 subtype.skip_binder().b);
505 Err(FulfillmentErrorCode::CodeSubtypeError(expected_found, err))
510 ty::Predicate::ConstEvaluatable(def_id, substs) => {
511 match selcx.tcx().lift_to_global(&obligation.param_env) {
516 match selcx.tcx().lift_to_global(&substs) {
518 pending_obligation.stalled_on = substs.types().collect();
522 match selcx.tcx().at(obligation.cause.span)
523 .const_eval(param_env.and((def_id, substs))) {
524 Ok(_) => Ok(Some(vec![])),
525 Err(e) => Err(CodeSelectionError(ConstEvalFailure(e)))
535 fn to_fulfillment_error<'tcx>(
536 error: Error<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>>)
537 -> FulfillmentError<'tcx>
539 let obligation = error.backtrace.into_iter().next().unwrap().obligation;
540 FulfillmentError::new(obligation, error.error)