]> git.lizzy.rs Git - rust.git/blob - src/librustc_trait_selection/traits/wf.rs
afa2270b7af0f2b5d193cad496f023cf6ca71aa6
[rust.git] / src / librustc_trait_selection / traits / wf.rs
1 use crate::infer::InferCtxt;
2 use crate::opaque_types::required_region_bounds;
3 use crate::traits;
4 use rustc_hir as hir;
5 use rustc_hir::def_id::DefId;
6 use rustc_hir::lang_items;
7 use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef};
8 use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};
9 use rustc_span::Span;
10 use std::rc::Rc;
11
12 /// Returns the set of obligations needed to make `arg` well-formed.
13 /// If `arg` contains unresolved inference variables, this may include
14 /// further WF obligations. However, if `arg` IS an unresolved
15 /// inference variable, returns `None`, because we are not able to
16 /// make any progress at all. This is to prevent "livelock" where we
17 /// say "$0 is WF if $0 is WF".
18 pub fn obligations<'a, 'tcx>(
19     infcx: &InferCtxt<'a, 'tcx>,
20     param_env: ty::ParamEnv<'tcx>,
21     body_id: hir::HirId,
22     arg: GenericArg<'tcx>,
23     span: Span,
24 ) -> Option<Vec<traits::PredicateObligation<'tcx>>> {
25     // Handle the "livelock" case (see comment above) by bailing out if necessary.
26     let arg = match arg.unpack() {
27         GenericArgKind::Type(ty) => {
28             match ty.kind {
29                 ty::Infer(ty::TyVar(_)) => {
30                     let resolved_ty = infcx.shallow_resolve(ty);
31                     if resolved_ty == ty {
32                         // No progress, bail out to prevent "livelock".
33                         return None;
34                     }
35
36                     resolved_ty
37                 }
38                 _ => ty,
39             }
40             .into()
41         }
42         GenericArgKind::Const(ct) => {
43             match ct.val {
44                 ty::ConstKind::Infer(infer) => {
45                     let resolved = infcx.shallow_resolve(infer);
46                     if resolved == infer {
47                         // No progress.
48                         return None;
49                     }
50
51                     infcx.tcx.mk_const(ty::Const { val: ty::ConstKind::Infer(resolved), ty: ct.ty })
52                 }
53                 _ => ct,
54             }
55             .into()
56         }
57         // There is nothing we have to do for lifetimes.
58         GenericArgKind::Lifetime(..) => return Some(Vec::new()),
59     };
60
61     let mut wf = WfPredicates { infcx, param_env, body_id, span, out: vec![], item: None };
62     wf.compute(arg);
63     debug!("wf::obligations({:?}, body_id={:?}) = {:?}", arg, body_id, wf.out);
64
65     let result = wf.normalize();
66     debug!("wf::obligations({:?}, body_id={:?}) ~~> {:?}", arg, body_id, result);
67     Some(result)
68 }
69
70 /// Returns the obligations that make this trait reference
71 /// well-formed.  For example, if there is a trait `Set` defined like
72 /// `trait Set<K:Eq>`, then the trait reference `Foo: Set<Bar>` is WF
73 /// if `Bar: Eq`.
74 pub fn trait_obligations<'a, 'tcx>(
75     infcx: &InferCtxt<'a, 'tcx>,
76     param_env: ty::ParamEnv<'tcx>,
77     body_id: hir::HirId,
78     trait_ref: &ty::TraitRef<'tcx>,
79     span: Span,
80     item: Option<&'tcx hir::Item<'tcx>>,
81 ) -> Vec<traits::PredicateObligation<'tcx>> {
82     let mut wf = WfPredicates { infcx, param_env, body_id, span, out: vec![], item };
83     wf.compute_trait_ref(trait_ref, Elaborate::All);
84     wf.normalize()
85 }
86
87 pub fn predicate_obligations<'a, 'tcx>(
88     infcx: &InferCtxt<'a, 'tcx>,
89     param_env: ty::ParamEnv<'tcx>,
90     body_id: hir::HirId,
91     predicate: ty::Predicate<'tcx>,
92     span: Span,
93 ) -> Vec<traits::PredicateObligation<'tcx>> {
94     let mut wf = WfPredicates { infcx, param_env, body_id, span, out: vec![], item: None };
95
96     match predicate.kind() {
97         ty::PredicateKind::ForAll(binder) => {
98             // It's ok to skip the binder here because wf code is prepared for it
99             return predicate_obligations(infcx, param_env, body_id, binder.skip_binder(), span);
100         }
101         ty::PredicateKind::Trait(t, _) => {
102             wf.compute_trait_ref(&t.trait_ref, Elaborate::None);
103         }
104         ty::PredicateKind::RegionOutlives(..) => {}
105         &ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
106             wf.compute(ty.into());
107         }
108         ty::PredicateKind::Projection(t) => {
109             wf.compute_projection(t.projection_ty);
110             wf.compute(t.ty.into());
111         }
112         &ty::PredicateKind::WellFormed(arg) => {
113             wf.compute(arg);
114         }
115         ty::PredicateKind::ObjectSafe(_) => {}
116         ty::PredicateKind::ClosureKind(..) => {}
117         &ty::PredicateKind::Subtype(ty::SubtypePredicate { a, b, a_is_expected: _ }) => {
118             wf.compute(a.into());
119             wf.compute(b.into());
120         }
121         &ty::PredicateKind::ConstEvaluatable(def, substs) => {
122             let obligations = wf.nominal_obligations(def.did, substs);
123             wf.out.extend(obligations);
124
125             for arg in substs.iter() {
126                 wf.compute(arg);
127             }
128         }
129         &ty::PredicateKind::ConstEquate(c1, c2) => {
130             wf.compute(c1.into());
131             wf.compute(c2.into());
132         }
133     }
134
135     wf.normalize()
136 }
137
138 struct WfPredicates<'a, 'tcx> {
139     infcx: &'a InferCtxt<'a, 'tcx>,
140     param_env: ty::ParamEnv<'tcx>,
141     body_id: hir::HirId,
142     span: Span,
143     out: Vec<traits::PredicateObligation<'tcx>>,
144     item: Option<&'tcx hir::Item<'tcx>>,
145 }
146
147 /// Controls whether we "elaborate" supertraits and so forth on the WF
148 /// predicates. This is a kind of hack to address #43784. The
149 /// underlying problem in that issue was a trait structure like:
150 ///
151 /// ```
152 /// trait Foo: Copy { }
153 /// trait Bar: Foo { }
154 /// impl<T: Bar> Foo for T { }
155 /// impl<T> Bar for T { }
156 /// ```
157 ///
158 /// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
159 /// we decide that this is true because `T: Bar` is in the
160 /// where-clauses (and we can elaborate that to include `T:
161 /// Copy`). This wouldn't be a problem, except that when we check the
162 /// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
163 /// impl. And so nowhere did we check that `T: Copy` holds!
164 ///
165 /// To resolve this, we elaborate the WF requirements that must be
166 /// proven when checking impls. This means that (e.g.) the `impl Bar
167 /// for T` will be forced to prove not only that `T: Foo` but also `T:
168 /// Copy` (which it won't be able to do, because there is no `Copy`
169 /// impl for `T`).
170 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
171 enum Elaborate {
172     All,
173     None,
174 }
175
176 fn extend_cause_with_original_assoc_item_obligation<'tcx>(
177     tcx: TyCtxt<'tcx>,
178     trait_ref: &ty::TraitRef<'tcx>,
179     item: Option<&hir::Item<'tcx>>,
180     cause: &mut traits::ObligationCause<'tcx>,
181     pred: &ty::Predicate<'tcx>,
182     mut trait_assoc_items: impl Iterator<Item = &'tcx ty::AssocItem>,
183 ) {
184     debug!(
185         "extended_cause_with_original_assoc_item_obligation {:?} {:?} {:?} {:?}",
186         trait_ref, item, cause, pred
187     );
188     let items = match item {
189         Some(hir::Item { kind: hir::ItemKind::Impl { items, .. }, .. }) => items,
190         _ => return,
191     };
192     let fix_span =
193         |impl_item_ref: &hir::ImplItemRef<'_>| match tcx.hir().impl_item(impl_item_ref.id).kind {
194             hir::ImplItemKind::Const(ty, _) | hir::ImplItemKind::TyAlias(ty) => ty.span,
195             _ => impl_item_ref.span,
196         };
197
198     // It is fine to skip the binder as we don't care about regions here.
199     match pred.ignore_quantifiers().skip_binder().kind() {
200         ty::PredicateKind::Projection(proj) => {
201             // The obligation comes not from the current `impl` nor the `trait` being implemented,
202             // but rather from a "second order" obligation, where an associated type has a
203             // projection coming from another associated type. See
204             // `src/test/ui/associated-types/point-at-type-on-obligation-failure.rs` and
205             // `traits-assoc-type-in-supertrait-bad.rs`.
206             if let ty::Projection(projection_ty) = proj.ty.kind {
207                 let trait_assoc_item = tcx.associated_item(projection_ty.item_def_id);
208                 if let Some(impl_item_span) =
209                     items.iter().find(|item| item.ident == trait_assoc_item.ident).map(fix_span)
210                 {
211                     cause.make_mut().span = impl_item_span;
212                 }
213             }
214         }
215         ty::PredicateKind::Trait(pred, _) => {
216             // An associated item obligation born out of the `trait` failed to be met. An example
217             // can be seen in `ui/associated-types/point-at-type-on-obligation-failure-2.rs`.
218             debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred);
219             if let ty::Projection(ty::ProjectionTy { item_def_id, .. }) = pred.self_ty().kind {
220                 if let Some(impl_item_span) = trait_assoc_items
221                     .find(|i| i.def_id == item_def_id)
222                     .and_then(|trait_assoc_item| {
223                         items.iter().find(|i| i.ident == trait_assoc_item.ident).map(fix_span)
224                     })
225                 {
226                     cause.make_mut().span = impl_item_span;
227                 }
228             }
229         }
230         _ => {}
231     }
232 }
233
234 impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
235     fn tcx(&self) -> TyCtxt<'tcx> {
236         self.infcx.tcx
237     }
238
239     fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
240         traits::ObligationCause::new(self.span, self.body_id, code)
241     }
242
243     fn normalize(&mut self) -> Vec<traits::PredicateObligation<'tcx>> {
244         let cause = self.cause(traits::MiscObligation);
245         let infcx = &mut self.infcx;
246         let param_env = self.param_env;
247         let mut obligations = Vec::with_capacity(self.out.len());
248         for pred in &self.out {
249             assert!(!pred.has_escaping_bound_vars());
250             let mut selcx = traits::SelectionContext::new(infcx);
251             let i = obligations.len();
252             let value =
253                 traits::normalize_to(&mut selcx, param_env, cause.clone(), pred, &mut obligations);
254             obligations.insert(i, value);
255         }
256         obligations
257     }
258
259     /// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
260     fn compute_trait_ref(&mut self, trait_ref: &ty::TraitRef<'tcx>, elaborate: Elaborate) {
261         let tcx = self.infcx.tcx;
262         let obligations = self.nominal_obligations(trait_ref.def_id, trait_ref.substs);
263
264         debug!("compute_trait_ref obligations {:?}", obligations);
265         let cause = self.cause(traits::MiscObligation);
266         let param_env = self.param_env;
267
268         let item = self.item;
269
270         let extend = |obligation: traits::PredicateObligation<'tcx>| {
271             let mut cause = cause.clone();
272             if let Some(parent_trait_ref) = obligation.predicate.to_opt_poly_trait_ref() {
273                 let derived_cause = traits::DerivedObligationCause {
274                     parent_trait_ref,
275                     parent_code: Rc::new(obligation.cause.code.clone()),
276                 };
277                 cause.make_mut().code =
278                     traits::ObligationCauseCode::DerivedObligation(derived_cause);
279             }
280             extend_cause_with_original_assoc_item_obligation(
281                 tcx,
282                 trait_ref,
283                 item,
284                 &mut cause,
285                 &obligation.predicate,
286                 tcx.associated_items(trait_ref.def_id).in_definition_order(),
287             );
288             traits::Obligation::new(cause, param_env, obligation.predicate)
289         };
290
291         if let Elaborate::All = elaborate {
292             let implied_obligations = traits::util::elaborate_obligations(tcx, obligations);
293             let implied_obligations = implied_obligations.map(extend);
294             self.out.extend(implied_obligations);
295         } else {
296             self.out.extend(obligations);
297         }
298
299         let tcx = self.tcx();
300         self.out.extend(
301             trait_ref
302                 .substs
303                 .iter()
304                 .enumerate()
305                 .filter(|(_, arg)| {
306                     matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..))
307                 })
308                 .filter(|(_, arg)| !arg.has_escaping_bound_vars())
309                 .map(|(i, arg)| {
310                     let mut new_cause = cause.clone();
311                     // The first subst is the self ty - use the correct span for it.
312                     if i == 0 {
313                         if let Some(hir::ItemKind::Impl { self_ty, .. }) = item.map(|i| &i.kind) {
314                             new_cause.make_mut().span = self_ty.span;
315                         }
316                     }
317                     traits::Obligation::new(
318                         new_cause,
319                         param_env,
320                         ty::PredicateKind::WellFormed(arg).to_predicate(tcx),
321                     )
322                 }),
323         );
324     }
325
326     /// Pushes the obligations required for `trait_ref::Item` to be WF
327     /// into `self.out`.
328     fn compute_projection(&mut self, data: ty::ProjectionTy<'tcx>) {
329         // A projection is well-formed if (a) the trait ref itself is
330         // WF and (b) the trait-ref holds.  (It may also be
331         // normalizable and be WF that way.)
332         let trait_ref = data.trait_ref(self.infcx.tcx);
333         self.compute_trait_ref(&trait_ref, Elaborate::None);
334
335         if !data.has_escaping_bound_vars() {
336             let predicate = trait_ref.without_const().to_predicate(self.infcx.tcx);
337             let cause = self.cause(traits::ProjectionWf(data));
338             self.out.push(traits::Obligation::new(cause, self.param_env, predicate));
339         }
340     }
341
342     fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
343         if !subty.has_escaping_bound_vars() {
344             let cause = self.cause(cause);
345             let trait_ref = ty::TraitRef {
346                 def_id: self.infcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
347                 substs: self.infcx.tcx.mk_substs_trait(subty, &[]),
348             };
349             self.out.push(traits::Obligation::new(
350                 cause,
351                 self.param_env,
352                 trait_ref.without_const().to_predicate(self.infcx.tcx),
353             ));
354         }
355     }
356
357     /// Pushes all the predicates needed to validate that `ty` is WF into `out`.
358     fn compute(&mut self, arg: GenericArg<'tcx>) {
359         let mut walker = arg.walk();
360         let param_env = self.param_env;
361         while let Some(arg) = walker.next() {
362             let ty = match arg.unpack() {
363                 GenericArgKind::Type(ty) => ty,
364
365                 // No WF constraints for lifetimes being present, any outlives
366                 // obligations are handled by the parent (e.g. `ty::Ref`).
367                 GenericArgKind::Lifetime(_) => continue,
368
369                 GenericArgKind::Const(constant) => {
370                     match constant.val {
371                         ty::ConstKind::Unevaluated(def, substs, promoted) => {
372                             assert!(promoted.is_none());
373
374                             let obligations = self.nominal_obligations(def.did, substs);
375                             self.out.extend(obligations);
376
377                             let predicate = ty::PredicateKind::ConstEvaluatable(def, substs)
378                                 .to_predicate(self.tcx());
379                             let cause = self.cause(traits::MiscObligation);
380                             self.out.push(traits::Obligation::new(
381                                 cause,
382                                 self.param_env,
383                                 predicate,
384                             ));
385                         }
386                         ty::ConstKind::Infer(infer) => {
387                             let resolved = self.infcx.shallow_resolve(infer);
388                             // the `InferConst` changed, meaning that we made progress.
389                             if resolved != infer {
390                                 let cause = self.cause(traits::MiscObligation);
391
392                                 let resolved_constant = self.infcx.tcx.mk_const(ty::Const {
393                                     val: ty::ConstKind::Infer(resolved),
394                                     ..*constant
395                                 });
396                                 self.out.push(traits::Obligation::new(
397                                     cause,
398                                     self.param_env,
399                                     ty::PredicateKind::WellFormed(resolved_constant.into())
400                                         .to_predicate(self.tcx()),
401                                 ));
402                             }
403                         }
404                         ty::ConstKind::Error(_)
405                         | ty::ConstKind::Param(_)
406                         | ty::ConstKind::Bound(..)
407                         | ty::ConstKind::Placeholder(..) => {
408                             // These variants are trivially WF, so nothing to do here.
409                         }
410                         ty::ConstKind::Value(..) => {
411                             // FIXME: Enforce that values are structurally-matchable.
412                         }
413                     }
414                     continue;
415                 }
416             };
417
418             match ty.kind {
419                 ty::Bool
420                 | ty::Char
421                 | ty::Int(..)
422                 | ty::Uint(..)
423                 | ty::Float(..)
424                 | ty::Error(_)
425                 | ty::Str
426                 | ty::GeneratorWitness(..)
427                 | ty::Never
428                 | ty::Param(_)
429                 | ty::Bound(..)
430                 | ty::Placeholder(..)
431                 | ty::Foreign(..) => {
432                     // WfScalar, WfParameter, etc
433                 }
434
435                 // Can only infer to `ty::Int(_) | ty::Uint(_)`.
436                 ty::Infer(ty::IntVar(_)) => {}
437
438                 // Can only infer to `ty::Float(_)`.
439                 ty::Infer(ty::FloatVar(_)) => {}
440
441                 ty::Slice(subty) => {
442                     self.require_sized(subty, traits::SliceOrArrayElem);
443                 }
444
445                 ty::Array(subty, _) => {
446                     self.require_sized(subty, traits::SliceOrArrayElem);
447                     // Note that we handle the len is implicitly checked while walking `arg`.
448                 }
449
450                 ty::Tuple(ref tys) => {
451                     if let Some((_last, rest)) = tys.split_last() {
452                         for elem in rest {
453                             self.require_sized(elem.expect_ty(), traits::TupleElem);
454                         }
455                     }
456                 }
457
458                 ty::RawPtr(_) => {
459                     // Simple cases that are WF if their type args are WF.
460                 }
461
462                 ty::Projection(data) => {
463                     walker.skip_current_subtree(); // Subtree handled by compute_projection.
464                     self.compute_projection(data);
465                 }
466
467                 ty::Adt(def, substs) => {
468                     // WfNominalType
469                     let obligations = self.nominal_obligations(def.did, substs);
470                     self.out.extend(obligations);
471                 }
472
473                 ty::FnDef(did, substs) => {
474                     let obligations = self.nominal_obligations(did, substs);
475                     self.out.extend(obligations);
476                 }
477
478                 ty::Ref(r, rty, _) => {
479                     // WfReference
480                     if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
481                         let cause = self.cause(traits::ReferenceOutlivesReferent(ty));
482                         self.out.push(traits::Obligation::new(
483                             cause,
484                             param_env,
485                             ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(rty, r))
486                                 .to_predicate(self.tcx()),
487                         ));
488                     }
489                 }
490
491                 ty::Generator(..) => {
492                     // Walk ALL the types in the generator: this will
493                     // include the upvar types as well as the yield
494                     // type. Note that this is mildly distinct from
495                     // the closure case, where we have to be careful
496                     // about the signature of the closure. We don't
497                     // have the problem of implied bounds here since
498                     // generators don't take arguments.
499                 }
500
501                 ty::Closure(_, substs) => {
502                     // Only check the upvar types for WF, not the rest
503                     // of the types within. This is needed because we
504                     // capture the signature and it may not be WF
505                     // without the implied bounds. Consider a closure
506                     // like `|x: &'a T|` -- it may be that `T: 'a` is
507                     // not known to hold in the creator's context (and
508                     // indeed the closure may not be invoked by its
509                     // creator, but rather turned to someone who *can*
510                     // verify that).
511                     //
512                     // The special treatment of closures here really
513                     // ought not to be necessary either; the problem
514                     // is related to #25860 -- there is no way for us
515                     // to express a fn type complete with the implied
516                     // bounds that it is assuming. I think in reality
517                     // the WF rules around fn are a bit messed up, and
518                     // that is the rot problem: `fn(&'a T)` should
519                     // probably always be WF, because it should be
520                     // shorthand for something like `where(T: 'a) {
521                     // fn(&'a T) }`, as discussed in #25860.
522                     //
523                     // Note that we are also skipping the generic
524                     // types. This is consistent with the `outlives`
525                     // code, but anyway doesn't matter: within the fn
526                     // body where they are created, the generics will
527                     // always be WF, and outside of that fn body we
528                     // are not directly inspecting closure types
529                     // anyway, except via auto trait matching (which
530                     // only inspects the upvar types).
531                     walker.skip_current_subtree(); // subtree handled below
532                     for upvar_ty in substs.as_closure().upvar_tys() {
533                         // FIXME(eddyb) add the type to `walker` instead of recursing.
534                         self.compute(upvar_ty.into());
535                     }
536                 }
537
538                 ty::FnPtr(_) => {
539                     // let the loop iterate into the argument/return
540                     // types appearing in the fn signature
541                 }
542
543                 ty::Opaque(did, substs) => {
544                     // all of the requirements on type parameters
545                     // should've been checked by the instantiation
546                     // of whatever returned this exact `impl Trait`.
547
548                     // for named opaque `impl Trait` types we still need to check them
549                     if ty::is_impl_trait_defn(self.infcx.tcx, did).is_none() {
550                         let obligations = self.nominal_obligations(did, substs);
551                         self.out.extend(obligations);
552                     }
553                 }
554
555                 ty::Dynamic(data, r) => {
556                     // WfObject
557                     //
558                     // Here, we defer WF checking due to higher-ranked
559                     // regions. This is perhaps not ideal.
560                     self.from_object_ty(ty, data, r);
561
562                     // FIXME(#27579) RFC also considers adding trait
563                     // obligations that don't refer to Self and
564                     // checking those
565
566                     let defer_to_coercion = self.tcx().features().object_safe_for_dispatch;
567
568                     if !defer_to_coercion {
569                         let cause = self.cause(traits::MiscObligation);
570                         let component_traits = data.auto_traits().chain(data.principal_def_id());
571                         let tcx = self.tcx();
572                         self.out.extend(component_traits.map(|did| {
573                             traits::Obligation::new(
574                                 cause.clone(),
575                                 param_env,
576                                 ty::PredicateKind::ObjectSafe(did).to_predicate(tcx),
577                             )
578                         }));
579                     }
580                 }
581
582                 // Inference variables are the complicated case, since we don't
583                 // know what type they are. We do two things:
584                 //
585                 // 1. Check if they have been resolved, and if so proceed with
586                 //    THAT type.
587                 // 2. If not, we've at least simplified things (e.g., we went
588                 //    from `Vec<$0>: WF` to `$0: WF`), so we can
589                 //    register a pending obligation and keep
590                 //    moving. (Goal is that an "inductive hypothesis"
591                 //    is satisfied to ensure termination.)
592                 // See also the comment on `fn obligations`, describing "livelock"
593                 // prevention, which happens before this can be reached.
594                 ty::Infer(_) => {
595                     let ty = self.infcx.shallow_resolve(ty);
596                     if let ty::Infer(ty::TyVar(_)) = ty.kind {
597                         // Not yet resolved, but we've made progress.
598                         let cause = self.cause(traits::MiscObligation);
599                         self.out.push(traits::Obligation::new(
600                             cause,
601                             param_env,
602                             ty::PredicateKind::WellFormed(ty.into()).to_predicate(self.tcx()),
603                         ));
604                     } else {
605                         // Yes, resolved, proceed with the result.
606                         // FIXME(eddyb) add the type to `walker` instead of recursing.
607                         self.compute(ty.into());
608                     }
609                 }
610             }
611         }
612     }
613
614     fn nominal_obligations(
615         &mut self,
616         def_id: DefId,
617         substs: SubstsRef<'tcx>,
618     ) -> Vec<traits::PredicateObligation<'tcx>> {
619         let predicates = self.infcx.tcx.predicates_of(def_id).instantiate(self.infcx.tcx, substs);
620         predicates
621             .predicates
622             .into_iter()
623             .zip(predicates.spans.into_iter())
624             .map(|(pred, span)| {
625                 let cause = self.cause(traits::BindingObligation(def_id, span));
626                 traits::Obligation::new(cause, self.param_env, pred)
627             })
628             .filter(|pred| !pred.has_escaping_bound_vars())
629             .collect()
630     }
631
632     fn from_object_ty(
633         &mut self,
634         ty: Ty<'tcx>,
635         data: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
636         region: ty::Region<'tcx>,
637     ) {
638         // Imagine a type like this:
639         //
640         //     trait Foo { }
641         //     trait Bar<'c> : 'c { }
642         //
643         //     &'b (Foo+'c+Bar<'d>)
644         //         ^
645         //
646         // In this case, the following relationships must hold:
647         //
648         //     'b <= 'c
649         //     'd <= 'c
650         //
651         // The first conditions is due to the normal region pointer
652         // rules, which say that a reference cannot outlive its
653         // referent.
654         //
655         // The final condition may be a bit surprising. In particular,
656         // you may expect that it would have been `'c <= 'd`, since
657         // usually lifetimes of outer things are conservative
658         // approximations for inner things. However, it works somewhat
659         // differently with trait objects: here the idea is that if the
660         // user specifies a region bound (`'c`, in this case) it is the
661         // "master bound" that *implies* that bounds from other traits are
662         // all met. (Remember that *all bounds* in a type like
663         // `Foo+Bar+Zed` must be met, not just one, hence if we write
664         // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
665         // 'y.)
666         //
667         // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
668         // am looking forward to the future here.
669         if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
670             let implicit_bounds = object_region_bounds(self.infcx.tcx, data);
671
672             let explicit_bound = region;
673
674             self.out.reserve(implicit_bounds.len());
675             for implicit_bound in implicit_bounds {
676                 let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
677                 let outlives =
678                     ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
679                 self.out.push(traits::Obligation::new(
680                     cause,
681                     self.param_env,
682                     outlives.to_predicate(self.infcx.tcx),
683                 ));
684             }
685         }
686     }
687 }
688
689 /// Given an object type like `SomeTrait + Send`, computes the lifetime
690 /// bounds that must hold on the elided self type. These are derived
691 /// from the declarations of `SomeTrait`, `Send`, and friends -- if
692 /// they declare `trait SomeTrait : 'static`, for example, then
693 /// `'static` would appear in the list. The hard work is done by
694 /// `infer::required_region_bounds`, see that for more information.
695 pub fn object_region_bounds<'tcx>(
696     tcx: TyCtxt<'tcx>,
697     existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
698 ) -> Vec<ty::Region<'tcx>> {
699     // Since we don't actually *know* the self type for an object,
700     // this "open(err)" serves as a kind of dummy standin -- basically
701     // a placeholder type.
702     let open_ty = tcx.mk_ty_infer(ty::FreshTy(0));
703
704     let predicates = existential_predicates.iter().filter_map(|predicate| {
705         if let ty::ExistentialPredicate::Projection(_) = predicate.skip_binder() {
706             None
707         } else {
708             Some(predicate.with_self_ty(tcx, open_ty))
709         }
710     });
711
712     required_region_bounds(tcx, open_ty, predicates)
713 }