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