1 // Copyright 2012-2013 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 hir::def_id::DefId;
13 use ty::outlives::Component;
14 use ty::subst::Substs;
16 use ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable};
20 use middle::lang_items;
22 /// Returns the set of obligations needed to make `ty` well-formed.
23 /// If `ty` contains unresolved inference variables, this may include
24 /// further WF obligations. However, if `ty` IS an unresolved
25 /// inference variable, returns `None`, because we are not able to
26 /// make any progress at all. This is to prevent "livelock" where we
27 /// say "$0 is WF if $0 is WF".
28 pub fn obligations<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
29 param_env: ty::ParamEnv<'tcx>,
33 -> Option<Vec<traits::PredicateObligation<'tcx>>>
35 let mut wf = WfPredicates { infcx: infcx,
41 debug!("wf::obligations({:?}, body_id={:?}) = {:?}", ty, body_id, wf.out);
42 let result = wf.normalize();
43 debug!("wf::obligations({:?}, body_id={:?}) ~~> {:?}", ty, body_id, result);
46 None // no progress made, return None
50 /// Returns the obligations that make this trait reference
51 /// well-formed. For example, if there is a trait `Set` defined like
52 /// `trait Set<K:Eq>`, then the trait reference `Foo: Set<Bar>` is WF
54 pub fn trait_obligations<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
55 param_env: ty::ParamEnv<'tcx>,
57 trait_ref: &ty::TraitRef<'tcx>,
59 -> Vec<traits::PredicateObligation<'tcx>>
61 let mut wf = WfPredicates { infcx, param_env, body_id, span, out: vec![] };
62 wf.compute_trait_ref(trait_ref);
66 pub fn predicate_obligations<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
67 param_env: ty::ParamEnv<'tcx>,
69 predicate: &ty::Predicate<'tcx>,
71 -> Vec<traits::PredicateObligation<'tcx>>
73 let mut wf = WfPredicates { infcx, param_env, body_id, span, out: vec![] };
75 // (*) ok to skip binders, because wf code is prepared for it
77 ty::Predicate::Trait(ref t) => {
78 wf.compute_trait_ref(&t.skip_binder().trait_ref); // (*)
80 ty::Predicate::Equate(ref t) => {
81 wf.compute(t.skip_binder().0);
82 wf.compute(t.skip_binder().1);
84 ty::Predicate::RegionOutlives(..) => {
86 ty::Predicate::TypeOutlives(ref t) => {
87 wf.compute(t.skip_binder().0);
89 ty::Predicate::Projection(ref t) => {
90 let t = t.skip_binder(); // (*)
91 wf.compute_projection(t.projection_ty);
94 ty::Predicate::WellFormed(t) => {
97 ty::Predicate::ObjectSafe(_) => {
99 ty::Predicate::ClosureKind(..) => {
101 ty::Predicate::Subtype(ref data) => {
102 wf.compute(data.skip_binder().a); // (*)
103 wf.compute(data.skip_binder().b); // (*)
110 /// Implied bounds are region relationships that we deduce
111 /// automatically. The idea is that (e.g.) a caller must check that a
112 /// function's argument types are well-formed immediately before
113 /// calling that fn, and hence the *callee* can assume that its
114 /// argument types are well-formed. This may imply certain relationships
115 /// between generic parameters. For example:
117 /// fn foo<'a,T>(x: &'a T)
119 /// can only be called with a `'a` and `T` such that `&'a T` is WF.
120 /// For `&'a T` to be WF, `T: 'a` must hold. So we can assume `T: 'a`.
122 pub enum ImpliedBound<'tcx> {
123 RegionSubRegion(ty::Region<'tcx>, ty::Region<'tcx>),
124 RegionSubParam(ty::Region<'tcx>, ty::ParamTy),
125 RegionSubProjection(ty::Region<'tcx>, ty::ProjectionTy<'tcx>),
128 /// Compute the implied bounds that a callee/impl can assume based on
129 /// the fact that caller/projector has ensured that `ty` is WF. See
130 /// the `ImpliedBound` type for more details.
131 pub fn implied_bounds<'a, 'gcx, 'tcx>(
132 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
133 param_env: ty::ParamEnv<'tcx>,
134 body_id: ast::NodeId,
137 -> Vec<ImpliedBound<'tcx>>
139 // Sometimes when we ask what it takes for T: WF, we get back that
140 // U: WF is required; in that case, we push U onto this stack and
141 // process it next. Currently (at least) these resulting
142 // predicates are always guaranteed to be a subset of the original
143 // type, so we need not fear non-termination.
144 let mut wf_types = vec![ty];
146 let mut implied_bounds = vec![];
148 while let Some(ty) = wf_types.pop() {
149 // Compute the obligations for `ty` to be well-formed. If `ty` is
150 // an unresolved inference variable, just substituted an empty set
151 // -- because the return type here is going to be things we *add*
152 // to the environment, it's always ok for this set to be smaller
153 // than the ultimate set. (Note: normally there won't be
154 // unresolved inference variables here anyway, but there might be
155 // during typeck under some circumstances.)
156 let obligations = obligations(infcx, param_env, body_id, ty, span).unwrap_or(vec![]);
158 // From the full set of obligations, just filter down to the
159 // region relationships.
160 implied_bounds.extend(
163 .flat_map(|obligation| {
164 assert!(!obligation.has_escaping_regions());
165 match obligation.predicate {
166 ty::Predicate::Trait(..) |
167 ty::Predicate::Equate(..) |
168 ty::Predicate::Subtype(..) |
169 ty::Predicate::Projection(..) |
170 ty::Predicate::ClosureKind(..) |
171 ty::Predicate::ObjectSafe(..) =>
174 ty::Predicate::WellFormed(subty) => {
175 wf_types.push(subty);
179 ty::Predicate::RegionOutlives(ref data) =>
180 match infcx.tcx.no_late_bound_regions(data) {
183 Some(ty::OutlivesPredicate(r_a, r_b)) =>
184 vec![ImpliedBound::RegionSubRegion(r_b, r_a)],
187 ty::Predicate::TypeOutlives(ref data) =>
188 match infcx.tcx.no_late_bound_regions(data) {
190 Some(ty::OutlivesPredicate(ty_a, r_b)) => {
191 let ty_a = infcx.resolve_type_vars_if_possible(&ty_a);
192 let components = infcx.tcx.outlives_components(ty_a);
193 implied_bounds_from_components(r_b, components)
202 /// When we have an implied bound that `T: 'a`, we can further break
203 /// this down to determine what relationships would have to hold for
204 /// `T: 'a` to hold. We get to assume that the caller has validated
205 /// those relationships.
206 fn implied_bounds_from_components<'tcx>(sub_region: ty::Region<'tcx>,
207 sup_components: Vec<Component<'tcx>>)
208 -> Vec<ImpliedBound<'tcx>>
212 .flat_map(|component| {
214 Component::Region(r) =>
215 vec![ImpliedBound::RegionSubRegion(sub_region, r)],
216 Component::Param(p) =>
217 vec![ImpliedBound::RegionSubParam(sub_region, p)],
218 Component::Projection(p) =>
219 vec![ImpliedBound::RegionSubProjection(sub_region, p)],
220 Component::EscapingProjection(_) =>
221 // If the projection has escaping regions, don't
222 // try to infer any implied bounds even for its
223 // free components. This is conservative, because
224 // the caller will still have to prove that those
225 // free components outlive `sub_region`. But the
226 // idea is that the WAY that the caller proves
227 // that may change in the future and we want to
228 // give ourselves room to get smarter here.
230 Component::UnresolvedInferenceVariable(..) =>
237 struct WfPredicates<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
238 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
239 param_env: ty::ParamEnv<'tcx>,
240 body_id: ast::NodeId,
242 out: Vec<traits::PredicateObligation<'tcx>>,
245 impl<'a, 'gcx, 'tcx> WfPredicates<'a, 'gcx, 'tcx> {
246 fn cause(&mut self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
247 traits::ObligationCause::new(self.span, self.body_id, code)
250 fn normalize(&mut self) -> Vec<traits::PredicateObligation<'tcx>> {
251 let cause = self.cause(traits::MiscObligation);
252 let infcx = &mut self.infcx;
253 let param_env = self.param_env;
255 .inspect(|pred| assert!(!pred.has_escaping_regions()))
257 let mut selcx = traits::SelectionContext::new(infcx);
258 let pred = traits::normalize(&mut selcx, param_env, cause.clone(), pred);
259 once(pred.value).chain(pred.obligations)
264 /// Pushes the obligations required for `trait_ref` to be WF into
266 fn compute_trait_ref(&mut self, trait_ref: &ty::TraitRef<'tcx>) {
267 let obligations = self.nominal_obligations(trait_ref.def_id, trait_ref.substs);
268 self.out.extend(obligations);
270 let cause = self.cause(traits::MiscObligation);
271 let param_env = self.param_env;
273 trait_ref.substs.types()
274 .filter(|ty| !ty.has_escaping_regions())
275 .map(|ty| traits::Obligation::new(cause.clone(),
277 ty::Predicate::WellFormed(ty))));
280 /// Pushes the obligations required for `trait_ref::Item` to be WF
282 fn compute_projection(&mut self, data: ty::ProjectionTy<'tcx>) {
283 // A projection is well-formed if (a) the trait ref itself is
284 // WF and (b) the trait-ref holds. (It may also be
285 // normalizable and be WF that way.)
287 self.compute_trait_ref(&data.trait_ref);
289 if !data.has_escaping_regions() {
290 let predicate = data.trait_ref.to_predicate();
291 let cause = self.cause(traits::ProjectionWf(data));
292 self.out.push(traits::Obligation::new(cause, self.param_env, predicate));
296 fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
297 if !subty.has_escaping_regions() {
298 let cause = self.cause(cause);
299 let trait_ref = ty::TraitRef {
300 def_id: self.infcx.tcx.require_lang_item(lang_items::SizedTraitLangItem),
301 substs: self.infcx.tcx.mk_substs_trait(subty, &[]),
303 self.out.push(traits::Obligation::new(cause, self.param_env, trait_ref.to_predicate()));
307 /// Push new obligations into `out`. Returns true if it was able
308 /// to generate all the predicates needed to validate that `ty0`
309 /// is WF. Returns false if `ty0` is an unresolved type variable,
310 /// in which case we are not able to simplify at all.
311 fn compute(&mut self, ty0: Ty<'tcx>) -> bool {
312 let mut subtys = ty0.walk();
313 let param_env = self.param_env;
314 while let Some(ty) = subtys.next() {
325 // WfScalar, WfParameter, etc
329 ty::TyArray(subty, _) => {
330 self.require_sized(subty, traits::SliceOrArrayElem);
333 ty::TyTuple(ref tys, _) => {
334 if let Some((_last, rest)) = tys.split_last() {
336 self.require_sized(elem, traits::TupleElem);
342 // simple cases that are WF if their type args are WF
345 ty::TyProjection(data) => {
346 subtys.skip_current_subtree(); // subtree handled by compute_projection
347 self.compute_projection(data);
350 ty::TyAdt(def, substs) => {
352 let obligations = self.nominal_obligations(def.did, substs);
353 self.out.extend(obligations);
356 ty::TyRef(r, mt) => {
358 if !r.has_escaping_regions() && !mt.ty.has_escaping_regions() {
359 let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
361 traits::Obligation::new(
364 ty::Predicate::TypeOutlives(
366 ty::OutlivesPredicate(mt.ty, r)))));
370 ty::TyClosure(..) => {
371 // the types in a closure are always the types of
372 // local variables (or possibly references to local
373 // variables), we'll walk those.
375 // (Though, local variables are probably not
376 // needed, as they are separately checked w/r/t
380 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
381 // let the loop iterate into the argument/return
382 // types appearing in the fn signature
386 // all of the requirements on type parameters
387 // should've been checked by the instantiation
388 // of whatever returned this exact `impl Trait`.
391 ty::TyDynamic(data, r) => {
394 // Here, we defer WF checking due to higher-ranked
395 // regions. This is perhaps not ideal.
396 self.from_object_ty(ty, data, r);
398 // FIXME(#27579) RFC also considers adding trait
399 // obligations that don't refer to Self and
402 let cause = self.cause(traits::MiscObligation);
403 let component_traits =
404 data.auto_traits().chain(data.principal().map(|p| p.def_id()));
406 component_traits.map(|did| traits::Obligation::new(
409 ty::Predicate::ObjectSafe(did)
414 // Inference variables are the complicated case, since we don't
415 // know what type they are. We do two things:
417 // 1. Check if they have been resolved, and if so proceed with
419 // 2. If not, check whether this is the type that we
420 // started with (ty0). In that case, we've made no
421 // progress at all, so return false. Otherwise,
422 // we've at least simplified things (i.e., we went
423 // from `Vec<$0>: WF` to `$0: WF`, so we can
424 // register a pending obligation and keep
425 // moving. (Goal is that an "inductive hypothesis"
426 // is satisfied to ensure termination.)
428 let ty = self.infcx.shallow_resolve(ty);
429 if let ty::TyInfer(_) = ty.sty { // not yet resolved...
430 if ty == ty0 { // ...this is the type we started from! no progress.
434 let cause = self.cause(traits::MiscObligation);
435 self.out.push( // ...not the type we started from, so we made progress.
436 traits::Obligation::new(cause,
438 ty::Predicate::WellFormed(ty)));
440 // Yes, resolved, proceed with the
441 // result. Should never return false because
442 // `ty` is not a TyInfer.
443 assert!(self.compute(ty));
449 // if we made it through that loop above, we made progress!
453 fn nominal_obligations(&mut self,
455 substs: &Substs<'tcx>)
456 -> Vec<traits::PredicateObligation<'tcx>>
459 self.infcx.tcx.predicates_of(def_id)
460 .instantiate(self.infcx.tcx, substs);
461 let cause = self.cause(traits::ItemObligation(def_id));
462 predicates.predicates
464 .map(|pred| traits::Obligation::new(cause.clone(),
467 .filter(|pred| !pred.has_escaping_regions())
471 fn from_object_ty(&mut self, ty: Ty<'tcx>,
472 data: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>,
473 region: ty::Region<'tcx>) {
474 // Imagine a type like this:
477 // trait Bar<'c> : 'c { }
479 // &'b (Foo+'c+Bar<'d>)
482 // In this case, the following relationships must hold:
487 // The first conditions is due to the normal region pointer
488 // rules, which say that a reference cannot outlive its
491 // The final condition may be a bit surprising. In particular,
492 // you may expect that it would have been `'c <= 'd`, since
493 // usually lifetimes of outer things are conservative
494 // approximations for inner things. However, it works somewhat
495 // differently with trait objects: here the idea is that if the
496 // user specifies a region bound (`'c`, in this case) it is the
497 // "master bound" that *implies* that bounds from other traits are
498 // all met. (Remember that *all bounds* in a type like
499 // `Foo+Bar+Zed` must be met, not just one, hence if we write
500 // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
503 // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
504 // am looking forward to the future here.
506 if !data.has_escaping_regions() {
507 let implicit_bounds =
508 object_region_bounds(self.infcx.tcx, data);
510 let explicit_bound = region;
512 for implicit_bound in implicit_bounds {
513 let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
514 let outlives = ty::Binder(ty::OutlivesPredicate(explicit_bound, implicit_bound));
515 self.out.push(traits::Obligation::new(cause,
517 outlives.to_predicate()));
523 /// Given an object type like `SomeTrait+Send`, computes the lifetime
524 /// bounds that must hold on the elided self type. These are derived
525 /// from the declarations of `SomeTrait`, `Send`, and friends -- if
526 /// they declare `trait SomeTrait : 'static`, for example, then
527 /// `'static` would appear in the list. The hard work is done by
528 /// `ty::required_region_bounds`, see that for more information.
529 pub fn object_region_bounds<'a, 'gcx, 'tcx>(
530 tcx: TyCtxt<'a, 'gcx, 'tcx>,
531 existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
532 -> Vec<ty::Region<'tcx>>
534 // Since we don't actually *know* the self type for an object,
535 // this "open(err)" serves as a kind of dummy standin -- basically
536 // a skolemized type.
537 let open_ty = tcx.mk_infer(ty::FreshTy(0));
539 let predicates = existential_predicates.iter().filter_map(|predicate| {
540 if let ty::ExistentialPredicate::Projection(_) = *predicate.skip_binder() {
543 Some(predicate.with_self_ty(tcx, open_ty))
547 tcx.required_region_bounds(open_ty, predicates)