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