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