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