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