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