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