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