rustc_trait_selection/traits/
wf.rs

1//! Core logic responsible for determining what it means for various type system
2//! primitives to be "well formed". Actually checking whether these primitives are
3//! well formed is performed elsewhere (e.g. during type checking or item well formedness
4//! checking).
5
6use std::iter;
7
8use rustc_hir as hir;
9use rustc_hir::def::DefKind;
10use rustc_hir::lang_items::LangItem;
11use rustc_infer::traits::{ObligationCauseCode, PredicateObligations};
12use rustc_middle::bug;
13use rustc_middle::ty::{
14    self, GenericArgsRef, Term, TermKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
15    TypeVisitableExt, TypeVisitor,
16};
17use rustc_session::parse::feature_err;
18use rustc_span::def_id::{DefId, LocalDefId};
19use rustc_span::{Span, sym};
20use tracing::{debug, instrument, trace};
21
22use crate::infer::InferCtxt;
23use crate::traits;
24
25/// Returns the set of obligations needed to make `arg` well-formed.
26/// If `arg` contains unresolved inference variables, this may include
27/// further WF obligations. However, if `arg` IS an unresolved
28/// inference variable, returns `None`, because we are not able to
29/// make any progress at all. This is to prevent cycles where we
30/// say "?0 is WF if ?0 is WF".
31pub fn obligations<'tcx>(
32    infcx: &InferCtxt<'tcx>,
33    param_env: ty::ParamEnv<'tcx>,
34    body_id: LocalDefId,
35    recursion_depth: usize,
36    term: Term<'tcx>,
37    span: Span,
38) -> Option<PredicateObligations<'tcx>> {
39    // Handle the "cycle" case (see comment above) by bailing out if necessary.
40    let term = match term.kind() {
41        TermKind::Ty(ty) => {
42            match ty.kind() {
43                ty::Infer(ty::TyVar(_)) => {
44                    let resolved_ty = infcx.shallow_resolve(ty);
45                    if resolved_ty == ty {
46                        // No progress, bail out to prevent cycles.
47                        return None;
48                    } else {
49                        resolved_ty
50                    }
51                }
52                _ => ty,
53            }
54            .into()
55        }
56        TermKind::Const(ct) => {
57            match ct.kind() {
58                ty::ConstKind::Infer(_) => {
59                    let resolved = infcx.shallow_resolve_const(ct);
60                    if resolved == ct {
61                        // No progress, bail out to prevent cycles.
62                        return None;
63                    } else {
64                        resolved
65                    }
66                }
67                _ => ct,
68            }
69            .into()
70        }
71    };
72
73    let mut wf = WfPredicates {
74        infcx,
75        param_env,
76        body_id,
77        span,
78        out: PredicateObligations::new(),
79        recursion_depth,
80        item: None,
81    };
82    wf.add_wf_preds_for_term(term);
83    debug!("wf::obligations({:?}, body_id={:?}) = {:?}", term, body_id, wf.out);
84
85    let result = wf.normalize(infcx);
86    debug!("wf::obligations({:?}, body_id={:?}) ~~> {:?}", term, body_id, result);
87    Some(result)
88}
89
90/// Compute the predicates that are required for a type to be well-formed.
91///
92/// This is only intended to be used in the new solver, since it does not
93/// take into account recursion depth or proper error-reporting spans.
94pub fn unnormalized_obligations<'tcx>(
95    infcx: &InferCtxt<'tcx>,
96    param_env: ty::ParamEnv<'tcx>,
97    term: Term<'tcx>,
98    span: Span,
99    body_id: LocalDefId,
100) -> Option<PredicateObligations<'tcx>> {
101    debug_assert_eq!(term, infcx.resolve_vars_if_possible(term));
102
103    // However, if `arg` IS an unresolved inference variable, returns `None`,
104    // because we are not able to make any progress at all. This is to prevent
105    // cycles where we say "?0 is WF if ?0 is WF".
106    if term.is_infer() {
107        return None;
108    }
109
110    let mut wf = WfPredicates {
111        infcx,
112        param_env,
113        body_id,
114        span,
115        out: PredicateObligations::new(),
116        recursion_depth: 0,
117        item: None,
118    };
119    wf.add_wf_preds_for_term(term);
120    Some(wf.out)
121}
122
123/// Returns the obligations that make this trait reference
124/// well-formed. For example, if there is a trait `Set` defined like
125/// `trait Set<K: Eq>`, then the trait bound `Foo: Set<Bar>` is WF
126/// if `Bar: Eq`.
127pub fn trait_obligations<'tcx>(
128    infcx: &InferCtxt<'tcx>,
129    param_env: ty::ParamEnv<'tcx>,
130    body_id: LocalDefId,
131    trait_pred: ty::TraitPredicate<'tcx>,
132    span: Span,
133    item: &'tcx hir::Item<'tcx>,
134) -> PredicateObligations<'tcx> {
135    let mut wf = WfPredicates {
136        infcx,
137        param_env,
138        body_id,
139        span,
140        out: PredicateObligations::new(),
141        recursion_depth: 0,
142        item: Some(item),
143    };
144    wf.add_wf_preds_for_trait_pred(trait_pred, Elaborate::All);
145    debug!(obligations = ?wf.out);
146    wf.normalize(infcx)
147}
148
149/// Returns the requirements for `clause` to be well-formed.
150///
151/// For example, if there is a trait `Set` defined like
152/// `trait Set<K: Eq>`, then the trait bound `Foo: Set<Bar>` is WF
153/// if `Bar: Eq`.
154#[instrument(skip(infcx), ret)]
155pub fn clause_obligations<'tcx>(
156    infcx: &InferCtxt<'tcx>,
157    param_env: ty::ParamEnv<'tcx>,
158    body_id: LocalDefId,
159    clause: ty::Clause<'tcx>,
160    span: Span,
161) -> PredicateObligations<'tcx> {
162    let mut wf = WfPredicates {
163        infcx,
164        param_env,
165        body_id,
166        span,
167        out: PredicateObligations::new(),
168        recursion_depth: 0,
169        item: None,
170    };
171
172    // It's ok to skip the binder here because wf code is prepared for it
173    match clause.kind().skip_binder() {
174        ty::ClauseKind::Trait(t) => {
175            wf.add_wf_preds_for_trait_pred(t, Elaborate::None);
176        }
177        ty::ClauseKind::HostEffect(..) => {
178            // Technically the well-formedness of this predicate is implied by
179            // the corresponding trait predicate it should've been generated beside.
180        }
181        ty::ClauseKind::RegionOutlives(..) => {}
182        ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
183            wf.add_wf_preds_for_term(ty.into());
184        }
185        ty::ClauseKind::Projection(t) => {
186            wf.add_wf_preds_for_alias_term(t.projection_term);
187            wf.add_wf_preds_for_term(t.term);
188        }
189        ty::ClauseKind::ConstArgHasType(ct, ty) => {
190            wf.add_wf_preds_for_term(ct.into());
191            wf.add_wf_preds_for_term(ty.into());
192        }
193        ty::ClauseKind::WellFormed(term) => {
194            wf.add_wf_preds_for_term(term);
195        }
196
197        ty::ClauseKind::ConstEvaluatable(ct) => {
198            wf.add_wf_preds_for_term(ct.into());
199        }
200        ty::ClauseKind::UnstableFeature(_) => {}
201    }
202
203    wf.normalize(infcx)
204}
205
206struct WfPredicates<'a, 'tcx> {
207    infcx: &'a InferCtxt<'tcx>,
208    param_env: ty::ParamEnv<'tcx>,
209    body_id: LocalDefId,
210    span: Span,
211    out: PredicateObligations<'tcx>,
212    recursion_depth: usize,
213    item: Option<&'tcx hir::Item<'tcx>>,
214}
215
216/// Controls whether we "elaborate" supertraits and so forth on the WF
217/// predicates. This is a kind of hack to address #43784. The
218/// underlying problem in that issue was a trait structure like:
219///
220/// ```ignore (illustrative)
221/// trait Foo: Copy { }
222/// trait Bar: Foo { }
223/// impl<T: Bar> Foo for T { }
224/// impl<T> Bar for T { }
225/// ```
226///
227/// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
228/// we decide that this is true because `T: Bar` is in the
229/// where-clauses (and we can elaborate that to include `T:
230/// Copy`). This wouldn't be a problem, except that when we check the
231/// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
232/// impl. And so nowhere did we check that `T: Copy` holds!
233///
234/// To resolve this, we elaborate the WF requirements that must be
235/// proven when checking impls. This means that (e.g.) the `impl Bar
236/// for T` will be forced to prove not only that `T: Foo` but also `T:
237/// Copy` (which it won't be able to do, because there is no `Copy`
238/// impl for `T`).
239#[derive(Debug, PartialEq, Eq, Copy, Clone)]
240enum Elaborate {
241    All,
242    None,
243}
244
245/// Points the cause span of a super predicate at the relevant associated type.
246///
247/// Given a trait impl item:
248///
249/// ```ignore (incomplete)
250/// impl TargetTrait for TargetType {
251///    type Assoc = SomeType;
252/// }
253/// ```
254///
255/// And a super predicate of `TargetTrait` that has any of the following forms:
256///
257/// 1. `<OtherType as OtherTrait>::Assoc == <TargetType as TargetTrait>::Assoc`
258/// 2. `<<TargetType as TargetTrait>::Assoc as OtherTrait>::Assoc == OtherType`
259/// 3. `<TargetType as TargetTrait>::Assoc: OtherTrait`
260///
261/// Replace the span of the cause with the span of the associated item:
262///
263/// ```ignore (incomplete)
264/// impl TargetTrait for TargetType {
265///     type Assoc = SomeType;
266/// //               ^^^^^^^^ this span
267/// }
268/// ```
269///
270/// Note that bounds that can be expressed as associated item bounds are **not**
271/// super predicates. This means that form 2 and 3 from above are only relevant if
272/// the [`GenericArgsRef`] of the projection type are not its identity arguments.
273fn extend_cause_with_original_assoc_item_obligation<'tcx>(
274    tcx: TyCtxt<'tcx>,
275    item: Option<&hir::Item<'tcx>>,
276    cause: &mut traits::ObligationCause<'tcx>,
277    pred: ty::Predicate<'tcx>,
278) {
279    debug!(?item, ?cause, ?pred, "extended_cause_with_original_assoc_item_obligation");
280    let (items, impl_def_id) = match item {
281        Some(hir::Item { kind: hir::ItemKind::Impl(impl_), owner_id, .. }) => {
282            (impl_.items, *owner_id)
283        }
284        _ => return,
285    };
286
287    let ty_to_impl_span = |ty: Ty<'_>| {
288        if let ty::Alias(ty::Projection, projection_ty) = ty.kind()
289            && let Some(&impl_item_id) =
290                tcx.impl_item_implementor_ids(impl_def_id).get(&projection_ty.def_id)
291            && let Some(impl_item) =
292                items.iter().find(|item| item.owner_id.to_def_id() == impl_item_id)
293        {
294            Some(tcx.hir_impl_item(*impl_item).expect_type().span)
295        } else {
296            None
297        }
298    };
299
300    // It is fine to skip the binder as we don't care about regions here.
301    match pred.kind().skip_binder() {
302        ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) => {
303            // Form 1: The obligation comes not from the current `impl` nor the `trait` being
304            // implemented, but rather from a "second order" obligation, where an associated
305            // type has a projection coming from another associated type.
306            // See `tests/ui/traits/assoc-type-in-superbad.rs` for an example.
307            if let Some(term_ty) = proj.term.as_type()
308                && let Some(impl_item_span) = ty_to_impl_span(term_ty)
309            {
310                cause.span = impl_item_span;
311            }
312
313            // Form 2: A projection obligation for an associated item failed to be met.
314            // We overwrite the span from above to ensure that a bound like
315            // `Self::Assoc1: Trait<OtherAssoc = Self::Assoc2>` gets the same
316            // span for both obligations that it is lowered to.
317            if let Some(impl_item_span) = ty_to_impl_span(proj.self_ty()) {
318                cause.span = impl_item_span;
319            }
320        }
321
322        ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
323            // Form 3: A trait obligation for an associated item failed to be met.
324            debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred);
325            if let Some(impl_item_span) = ty_to_impl_span(pred.self_ty()) {
326                cause.span = impl_item_span;
327            }
328        }
329        _ => {}
330    }
331}
332
333impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
334    fn tcx(&self) -> TyCtxt<'tcx> {
335        self.infcx.tcx
336    }
337
338    fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
339        traits::ObligationCause::new(self.span, self.body_id, code)
340    }
341
342    fn normalize(self, infcx: &InferCtxt<'tcx>) -> PredicateObligations<'tcx> {
343        // Do not normalize `wf` obligations with the new solver.
344        //
345        // The current deep normalization routine with the new solver does not
346        // handle ambiguity and the new solver correctly deals with unnnormalized goals.
347        // If the user relies on normalized types, e.g. for `fn implied_outlives_bounds`,
348        // it is their responsibility to normalize while avoiding ambiguity.
349        if infcx.next_trait_solver() {
350            return self.out;
351        }
352
353        let cause = self.cause(ObligationCauseCode::WellFormed(None));
354        let param_env = self.param_env;
355        let mut obligations = PredicateObligations::with_capacity(self.out.len());
356        for mut obligation in self.out {
357            assert!(!obligation.has_escaping_bound_vars());
358            let mut selcx = traits::SelectionContext::new(infcx);
359            // Don't normalize the whole obligation, the param env is either
360            // already normalized, or we're currently normalizing the
361            // param_env. Either way we should only normalize the predicate.
362            let normalized_predicate = traits::normalize::normalize_with_depth_to(
363                &mut selcx,
364                param_env,
365                cause.clone(),
366                self.recursion_depth,
367                obligation.predicate,
368                &mut obligations,
369            );
370            obligation.predicate = normalized_predicate;
371            obligations.push(obligation);
372        }
373        obligations
374    }
375
376    /// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
377    fn add_wf_preds_for_trait_pred(
378        &mut self,
379        trait_pred: ty::TraitPredicate<'tcx>,
380        elaborate: Elaborate,
381    ) {
382        let tcx = self.tcx();
383        let trait_ref = trait_pred.trait_ref;
384
385        // Negative trait predicates don't require supertraits to hold, just
386        // that their args are WF.
387        if trait_pred.polarity == ty::PredicatePolarity::Negative {
388            self.add_wf_preds_for_negative_trait_pred(trait_ref);
389            return;
390        }
391
392        // if the trait predicate is not const, the wf obligations should not be const as well.
393        let obligations = self.nominal_obligations(trait_ref.def_id, trait_ref.args);
394
395        debug!("compute_trait_pred obligations {:?}", obligations);
396        let param_env = self.param_env;
397        let depth = self.recursion_depth;
398
399        let item = self.item;
400
401        let extend = |traits::PredicateObligation { predicate, mut cause, .. }| {
402            if let Some(parent_trait_pred) = predicate.as_trait_clause() {
403                cause = cause.derived_cause(
404                    parent_trait_pred,
405                    traits::ObligationCauseCode::WellFormedDerived,
406                );
407            }
408            extend_cause_with_original_assoc_item_obligation(tcx, item, &mut cause, predicate);
409            traits::Obligation::with_depth(tcx, cause, depth, param_env, predicate)
410        };
411
412        if let Elaborate::All = elaborate {
413            let implied_obligations = traits::util::elaborate(tcx, obligations);
414            let implied_obligations = implied_obligations.map(extend);
415            self.out.extend(implied_obligations);
416        } else {
417            self.out.extend(obligations);
418        }
419
420        self.out.extend(
421            trait_ref
422                .args
423                .iter()
424                .enumerate()
425                .filter_map(|(i, arg)| arg.as_term().map(|t| (i, t)))
426                .filter(|(_, term)| !term.has_escaping_bound_vars())
427                .map(|(i, term)| {
428                    let mut cause = traits::ObligationCause::misc(self.span, self.body_id);
429                    // The first arg is the self ty - use the correct span for it.
430                    if i == 0 {
431                        if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) =
432                            item.map(|i| &i.kind)
433                        {
434                            cause.span = self_ty.span;
435                        }
436                    }
437                    traits::Obligation::with_depth(
438                        tcx,
439                        cause,
440                        depth,
441                        param_env,
442                        ty::ClauseKind::WellFormed(term),
443                    )
444                }),
445        );
446    }
447
448    // Compute the obligations that are required for `trait_ref` to be WF,
449    // given that it is a *negative* trait predicate.
450    fn add_wf_preds_for_negative_trait_pred(&mut self, trait_ref: ty::TraitRef<'tcx>) {
451        for arg in trait_ref.args {
452            if let Some(term) = arg.as_term() {
453                self.add_wf_preds_for_term(term);
454            }
455        }
456    }
457
458    /// Pushes the obligations required for an alias (except inherent) to be WF
459    /// into `self.out`.
460    fn add_wf_preds_for_alias_term(&mut self, data: ty::AliasTerm<'tcx>) {
461        // A projection is well-formed if
462        //
463        // (a) its predicates hold (*)
464        // (b) its args are wf
465        //
466        // (*) The predicates of an associated type include the predicates of
467        //     the trait that it's contained in. For example, given
468        //
469        // trait A<T>: Clone {
470        //     type X where T: Copy;
471        // }
472        //
473        // The predicates of `<() as A<i32>>::X` are:
474        // [
475        //     `(): Sized`
476        //     `(): Clone`
477        //     `(): A<i32>`
478        //     `i32: Sized`
479        //     `i32: Clone`
480        //     `i32: Copy`
481        // ]
482        let obligations = self.nominal_obligations(data.def_id, data.args);
483        self.out.extend(obligations);
484
485        self.add_wf_preds_for_projection_args(data.args);
486    }
487
488    /// Pushes the obligations required for an inherent alias to be WF
489    /// into `self.out`.
490    // FIXME(inherent_associated_types): Merge this function with `fn compute_alias`.
491    fn add_wf_preds_for_inherent_projection(&mut self, data: ty::AliasTerm<'tcx>) {
492        // An inherent projection is well-formed if
493        //
494        // (a) its predicates hold (*)
495        // (b) its args are wf
496        //
497        // (*) The predicates of an inherent associated type include the
498        //     predicates of the impl that it's contained in.
499
500        if !data.self_ty().has_escaping_bound_vars() {
501            // FIXME(inherent_associated_types): Should this happen inside of a snapshot?
502            // FIXME(inherent_associated_types): This is incompatible with the new solver and lazy norm!
503            let args = traits::project::compute_inherent_assoc_term_args(
504                &mut traits::SelectionContext::new(self.infcx),
505                self.param_env,
506                data,
507                self.cause(ObligationCauseCode::WellFormed(None)),
508                self.recursion_depth,
509                &mut self.out,
510            );
511            let obligations = self.nominal_obligations(data.def_id, args);
512            self.out.extend(obligations);
513        }
514
515        data.args.visit_with(self);
516    }
517
518    fn add_wf_preds_for_projection_args(&mut self, args: GenericArgsRef<'tcx>) {
519        let tcx = self.tcx();
520        let cause = self.cause(ObligationCauseCode::WellFormed(None));
521        let param_env = self.param_env;
522        let depth = self.recursion_depth;
523
524        self.out.extend(
525            args.iter()
526                .filter_map(|arg| arg.as_term())
527                .filter(|term| !term.has_escaping_bound_vars())
528                .map(|term| {
529                    traits::Obligation::with_depth(
530                        tcx,
531                        cause.clone(),
532                        depth,
533                        param_env,
534                        ty::ClauseKind::WellFormed(term),
535                    )
536                }),
537        );
538    }
539
540    fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
541        if !subty.has_escaping_bound_vars() {
542            let cause = self.cause(cause);
543            let trait_ref = ty::TraitRef::new(
544                self.tcx(),
545                self.tcx().require_lang_item(LangItem::Sized, cause.span),
546                [subty],
547            );
548            self.out.push(traits::Obligation::with_depth(
549                self.tcx(),
550                cause,
551                self.recursion_depth,
552                self.param_env,
553                ty::Binder::dummy(trait_ref),
554            ));
555        }
556    }
557
558    /// Pushes all the predicates needed to validate that `term` is WF into `out`.
559    #[instrument(level = "debug", skip(self))]
560    fn add_wf_preds_for_term(&mut self, term: Term<'tcx>) {
561        term.visit_with(self);
562        debug!(?self.out);
563    }
564
565    #[instrument(level = "debug", skip(self))]
566    fn nominal_obligations(
567        &mut self,
568        def_id: DefId,
569        args: GenericArgsRef<'tcx>,
570    ) -> PredicateObligations<'tcx> {
571        // PERF: `Sized`'s predicates include `MetaSized`, but both are compiler implemented marker
572        // traits, so `MetaSized` will always be WF if `Sized` is WF and vice-versa. Determining
573        // the nominal obligations of `Sized` would in-effect just elaborate `MetaSized` and make
574        // the compiler do a bunch of work needlessly.
575        if self.tcx().is_lang_item(def_id, LangItem::Sized) {
576            return Default::default();
577        }
578
579        let predicates = self.tcx().predicates_of(def_id);
580        let mut origins = vec![def_id; predicates.predicates.len()];
581        let mut head = predicates;
582        while let Some(parent) = head.parent {
583            head = self.tcx().predicates_of(parent);
584            origins.extend(iter::repeat(parent).take(head.predicates.len()));
585        }
586
587        let predicates = predicates.instantiate(self.tcx(), args);
588        trace!("{:#?}", predicates);
589        debug_assert_eq!(predicates.predicates.len(), origins.len());
590
591        iter::zip(predicates, origins.into_iter().rev())
592            .map(|((pred, span), origin_def_id)| {
593                let code = ObligationCauseCode::WhereClause(origin_def_id, span);
594                let cause = self.cause(code);
595                traits::Obligation::with_depth(
596                    self.tcx(),
597                    cause,
598                    self.recursion_depth,
599                    self.param_env,
600                    pred,
601                )
602            })
603            .filter(|pred| !pred.has_escaping_bound_vars())
604            .collect()
605    }
606
607    fn add_wf_preds_for_dyn_ty(
608        &mut self,
609        ty: Ty<'tcx>,
610        data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
611        region: ty::Region<'tcx>,
612    ) {
613        // Imagine a type like this:
614        //
615        //     trait Foo { }
616        //     trait Bar<'c> : 'c { }
617        //
618        //     &'b (Foo+'c+Bar<'d>)
619        //         ^
620        //
621        // In this case, the following relationships must hold:
622        //
623        //     'b <= 'c
624        //     'd <= 'c
625        //
626        // The first conditions is due to the normal region pointer
627        // rules, which say that a reference cannot outlive its
628        // referent.
629        //
630        // The final condition may be a bit surprising. In particular,
631        // you may expect that it would have been `'c <= 'd`, since
632        // usually lifetimes of outer things are conservative
633        // approximations for inner things. However, it works somewhat
634        // differently with trait objects: here the idea is that if the
635        // user specifies a region bound (`'c`, in this case) it is the
636        // "master bound" that *implies* that bounds from other traits are
637        // all met. (Remember that *all bounds* in a type like
638        // `Foo+Bar+Zed` must be met, not just one, hence if we write
639        // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
640        // 'y.)
641        //
642        // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
643        // am looking forward to the future here.
644        if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
645            let implicit_bounds = object_region_bounds(self.tcx(), data);
646
647            let explicit_bound = region;
648
649            self.out.reserve(implicit_bounds.len());
650            for implicit_bound in implicit_bounds {
651                let cause = self.cause(ObligationCauseCode::ObjectTypeBound(ty, explicit_bound));
652                let outlives =
653                    ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
654                self.out.push(traits::Obligation::with_depth(
655                    self.tcx(),
656                    cause,
657                    self.recursion_depth,
658                    self.param_env,
659                    outlives,
660                ));
661            }
662
663            // We don't add any wf predicates corresponding to the trait ref's generic arguments
664            // which allows code like this to compile:
665            // ```rust
666            // trait Trait<T: Sized> {}
667            // fn foo(_: &dyn Trait<[u32]>) {}
668            // ```
669        }
670    }
671
672    fn add_wf_preds_for_pat_ty(&mut self, base_ty: Ty<'tcx>, pat: ty::Pattern<'tcx>) {
673        let tcx = self.tcx();
674        match *pat {
675            ty::PatternKind::Range { start, end } => {
676                let mut check = |c| {
677                    let cause = self.cause(ObligationCauseCode::Misc);
678                    self.out.push(traits::Obligation::with_depth(
679                        tcx,
680                        cause.clone(),
681                        self.recursion_depth,
682                        self.param_env,
683                        ty::Binder::dummy(ty::PredicateKind::Clause(
684                            ty::ClauseKind::ConstArgHasType(c, base_ty),
685                        )),
686                    ));
687                    if !tcx.features().generic_pattern_types() {
688                        if c.has_param() {
689                            if self.span.is_dummy() {
690                                self.tcx()
691                                    .dcx()
692                                    .delayed_bug("feature error should be reported elsewhere, too");
693                            } else {
694                                feature_err(
695                                    &self.tcx().sess,
696                                    sym::generic_pattern_types,
697                                    self.span,
698                                    "wraparound pattern type ranges cause monomorphization time errors",
699                                )
700                                .emit();
701                            }
702                        }
703                    }
704                };
705                check(start);
706                check(end);
707            }
708            ty::PatternKind::Or(patterns) => {
709                for pat in patterns {
710                    self.add_wf_preds_for_pat_ty(base_ty, pat)
711                }
712            }
713        }
714    }
715}
716
717impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
718    fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
719        debug!("wf bounds for t={:?} t.kind={:#?}", t, t.kind());
720
721        let tcx = self.tcx();
722
723        match *t.kind() {
724            ty::Bool
725            | ty::Char
726            | ty::Int(..)
727            | ty::Uint(..)
728            | ty::Float(..)
729            | ty::Error(_)
730            | ty::Str
731            | ty::CoroutineWitness(..)
732            | ty::Never
733            | ty::Param(_)
734            | ty::Bound(..)
735            | ty::Placeholder(..)
736            | ty::Foreign(..) => {
737                // WfScalar, WfParameter, etc
738            }
739
740            // Can only infer to `ty::Int(_) | ty::Uint(_)`.
741            ty::Infer(ty::IntVar(_)) => {}
742
743            // Can only infer to `ty::Float(_)`.
744            ty::Infer(ty::FloatVar(_)) => {}
745
746            ty::Slice(subty) => {
747                self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
748            }
749
750            ty::Array(subty, len) => {
751                self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
752                // Note that the len being WF is implicitly checked while visiting.
753                // Here we just check that it's of type usize.
754                let cause = self.cause(ObligationCauseCode::ArrayLen(t));
755                self.out.push(traits::Obligation::with_depth(
756                    tcx,
757                    cause,
758                    self.recursion_depth,
759                    self.param_env,
760                    ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
761                        len,
762                        tcx.types.usize,
763                    ))),
764                ));
765            }
766
767            ty::Pat(base_ty, pat) => {
768                self.require_sized(base_ty, ObligationCauseCode::Misc);
769                self.add_wf_preds_for_pat_ty(base_ty, pat);
770            }
771
772            ty::Tuple(tys) => {
773                if let Some((_last, rest)) = tys.split_last() {
774                    for &elem in rest {
775                        self.require_sized(elem, ObligationCauseCode::TupleElem);
776                    }
777                }
778            }
779
780            ty::RawPtr(_, _) => {
781                // Simple cases that are WF if their type args are WF.
782            }
783
784            ty::Alias(ty::Projection | ty::Opaque | ty::Free, data) => {
785                let obligations = self.nominal_obligations(data.def_id, data.args);
786                self.out.extend(obligations);
787            }
788            ty::Alias(ty::Inherent, data) => {
789                self.add_wf_preds_for_inherent_projection(data.into());
790                return; // Subtree handled by compute_inherent_projection.
791            }
792
793            ty::Adt(def, args) => {
794                // WfNominalType
795                let obligations = self.nominal_obligations(def.did(), args);
796                self.out.extend(obligations);
797            }
798
799            ty::FnDef(did, args) => {
800                // HACK: Check the return type of function definitions for
801                // well-formedness to mostly fix #84533. This is still not
802                // perfect and there may be ways to abuse the fact that we
803                // ignore requirements with escaping bound vars. That's a
804                // more general issue however.
805                let fn_sig = tcx.fn_sig(did).instantiate(tcx, args);
806                fn_sig.output().skip_binder().visit_with(self);
807
808                let obligations = self.nominal_obligations(did, args);
809                self.out.extend(obligations);
810            }
811
812            ty::Ref(r, rty, _) => {
813                // WfReference
814                if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
815                    let cause = self.cause(ObligationCauseCode::ReferenceOutlivesReferent(t));
816                    self.out.push(traits::Obligation::with_depth(
817                        tcx,
818                        cause,
819                        self.recursion_depth,
820                        self.param_env,
821                        ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(
822                            ty::OutlivesPredicate(rty, r),
823                        ))),
824                    ));
825                }
826            }
827
828            ty::Coroutine(did, args, ..) => {
829                // Walk ALL the types in the coroutine: this will
830                // include the upvar types as well as the yield
831                // type. Note that this is mildly distinct from
832                // the closure case, where we have to be careful
833                // about the signature of the closure. We don't
834                // have the problem of implied bounds here since
835                // coroutines don't take arguments.
836                let obligations = self.nominal_obligations(did, args);
837                self.out.extend(obligations);
838            }
839
840            ty::Closure(did, args) => {
841                // Note that we cannot skip the generic types
842                // types. Normally, within the fn
843                // body where they are created, the generics will
844                // always be WF, and outside of that fn body we
845                // are not directly inspecting closure types
846                // anyway, except via auto trait matching (which
847                // only inspects the upvar types).
848                // But when a closure is part of a type-alias-impl-trait
849                // then the function that created the defining site may
850                // have had more bounds available than the type alias
851                // specifies. This may cause us to have a closure in the
852                // hidden type that is not actually well formed and
853                // can cause compiler crashes when the user abuses unsafe
854                // code to procure such a closure.
855                // See tests/ui/type-alias-impl-trait/wf_check_closures.rs
856                let obligations = self.nominal_obligations(did, args);
857                self.out.extend(obligations);
858                // Only check the upvar types for WF, not the rest
859                // of the types within. This is needed because we
860                // capture the signature and it may not be WF
861                // without the implied bounds. Consider a closure
862                // like `|x: &'a T|` -- it may be that `T: 'a` is
863                // not known to hold in the creator's context (and
864                // indeed the closure may not be invoked by its
865                // creator, but rather turned to someone who *can*
866                // verify that).
867                //
868                // The special treatment of closures here really
869                // ought not to be necessary either; the problem
870                // is related to #25860 -- there is no way for us
871                // to express a fn type complete with the implied
872                // bounds that it is assuming. I think in reality
873                // the WF rules around fn are a bit messed up, and
874                // that is the rot problem: `fn(&'a T)` should
875                // probably always be WF, because it should be
876                // shorthand for something like `where(T: 'a) {
877                // fn(&'a T) }`, as discussed in #25860.
878                let upvars = args.as_closure().tupled_upvars_ty();
879                return upvars.visit_with(self);
880            }
881
882            ty::CoroutineClosure(did, args) => {
883                // See the above comments. The same apply to coroutine-closures.
884                let obligations = self.nominal_obligations(did, args);
885                self.out.extend(obligations);
886                let upvars = args.as_coroutine_closure().tupled_upvars_ty();
887                return upvars.visit_with(self);
888            }
889
890            ty::FnPtr(..) => {
891                // Let the visitor iterate into the argument/return
892                // types appearing in the fn signature.
893            }
894            ty::UnsafeBinder(ty) => {
895                // FIXME(unsafe_binders): For now, we have no way to express
896                // that a type must be `ManuallyDrop` OR `Copy` (or a pointer).
897                if !ty.has_escaping_bound_vars() {
898                    self.out.push(traits::Obligation::new(
899                        self.tcx(),
900                        self.cause(ObligationCauseCode::Misc),
901                        self.param_env,
902                        ty.map_bound(|ty| {
903                            ty::TraitRef::new(
904                                self.tcx(),
905                                self.tcx().require_lang_item(
906                                    LangItem::BikeshedGuaranteedNoDrop,
907                                    self.span,
908                                ),
909                                [ty],
910                            )
911                        }),
912                    ));
913                }
914
915                // We recurse into the binder below.
916            }
917
918            ty::Dynamic(data, r, _) => {
919                // WfObject
920                //
921                // Here, we defer WF checking due to higher-ranked
922                // regions. This is perhaps not ideal.
923                self.add_wf_preds_for_dyn_ty(t, data, r);
924
925                // FIXME(#27579) RFC also considers adding trait
926                // obligations that don't refer to Self and
927                // checking those
928                if let Some(principal) = data.principal_def_id() {
929                    self.out.push(traits::Obligation::with_depth(
930                        tcx,
931                        self.cause(ObligationCauseCode::WellFormed(None)),
932                        self.recursion_depth,
933                        self.param_env,
934                        ty::Binder::dummy(ty::PredicateKind::DynCompatible(principal)),
935                    ));
936                }
937            }
938
939            // Inference variables are the complicated case, since we don't
940            // know what type they are. We do two things:
941            //
942            // 1. Check if they have been resolved, and if so proceed with
943            //    THAT type.
944            // 2. If not, we've at least simplified things (e.g., we went
945            //    from `Vec?0>: WF` to `?0: WF`), so we can
946            //    register a pending obligation and keep
947            //    moving. (Goal is that an "inductive hypothesis"
948            //    is satisfied to ensure termination.)
949            // See also the comment on `fn obligations`, describing cycle
950            // prevention, which happens before this can be reached.
951            ty::Infer(_) => {
952                let cause = self.cause(ObligationCauseCode::WellFormed(None));
953                self.out.push(traits::Obligation::with_depth(
954                    tcx,
955                    cause,
956                    self.recursion_depth,
957                    self.param_env,
958                    ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
959                        t.into(),
960                    ))),
961                ));
962            }
963        }
964
965        t.super_visit_with(self)
966    }
967
968    fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
969        let tcx = self.tcx();
970
971        match c.kind() {
972            ty::ConstKind::Unevaluated(uv) => {
973                if !c.has_escaping_bound_vars() {
974                    let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
975                        ty::ClauseKind::ConstEvaluatable(c),
976                    ));
977                    let cause = self.cause(ObligationCauseCode::WellFormed(None));
978                    self.out.push(traits::Obligation::with_depth(
979                        tcx,
980                        cause,
981                        self.recursion_depth,
982                        self.param_env,
983                        predicate,
984                    ));
985
986                    if tcx.def_kind(uv.def) == DefKind::AssocConst
987                        && tcx.def_kind(tcx.parent(uv.def)) == (DefKind::Impl { of_trait: false })
988                    {
989                        self.add_wf_preds_for_inherent_projection(uv.into());
990                        return; // Subtree is handled by above function
991                    } else {
992                        let obligations = self.nominal_obligations(uv.def, uv.args);
993                        self.out.extend(obligations);
994                    }
995                }
996            }
997            ty::ConstKind::Infer(_) => {
998                let cause = self.cause(ObligationCauseCode::WellFormed(None));
999
1000                self.out.push(traits::Obligation::with_depth(
1001                    tcx,
1002                    cause,
1003                    self.recursion_depth,
1004                    self.param_env,
1005                    ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1006                        c.into(),
1007                    ))),
1008                ));
1009            }
1010            ty::ConstKind::Expr(_) => {
1011                // FIXME(generic_const_exprs): this doesn't verify that given `Expr(N + 1)` the
1012                // trait bound `typeof(N): Add<typeof(1)>` holds. This is currently unnecessary
1013                // as `ConstKind::Expr` is only produced via normalization of `ConstKind::Unevaluated`
1014                // which means that the `DefId` would have been typeck'd elsewhere. However in
1015                // the future we may allow directly lowering to `ConstKind::Expr` in which case
1016                // we would not be proving bounds we should.
1017
1018                let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1019                    ty::ClauseKind::ConstEvaluatable(c),
1020                ));
1021                let cause = self.cause(ObligationCauseCode::WellFormed(None));
1022                self.out.push(traits::Obligation::with_depth(
1023                    tcx,
1024                    cause,
1025                    self.recursion_depth,
1026                    self.param_env,
1027                    predicate,
1028                ));
1029            }
1030
1031            ty::ConstKind::Error(_)
1032            | ty::ConstKind::Param(_)
1033            | ty::ConstKind::Bound(..)
1034            | ty::ConstKind::Placeholder(..) => {
1035                // These variants are trivially WF, so nothing to do here.
1036            }
1037            ty::ConstKind::Value(..) => {
1038                // FIXME: Enforce that values are structurally-matchable.
1039            }
1040        }
1041
1042        c.super_visit_with(self)
1043    }
1044
1045    fn visit_predicate(&mut self, _p: ty::Predicate<'tcx>) -> Self::Result {
1046        bug!("predicate should not be checked for well-formedness");
1047    }
1048}
1049
1050/// Given an object type like `SomeTrait + Send`, computes the lifetime
1051/// bounds that must hold on the elided self type. These are derived
1052/// from the declarations of `SomeTrait`, `Send`, and friends -- if
1053/// they declare `trait SomeTrait : 'static`, for example, then
1054/// `'static` would appear in the list.
1055///
1056/// N.B., in some cases, particularly around higher-ranked bounds,
1057/// this function returns a kind of conservative approximation.
1058/// That is, all regions returned by this function are definitely
1059/// required, but there may be other region bounds that are not
1060/// returned, as well as requirements like `for<'a> T: 'a`.
1061///
1062/// Requires that trait definitions have been processed so that we can
1063/// elaborate predicates and walk supertraits.
1064pub fn object_region_bounds<'tcx>(
1065    tcx: TyCtxt<'tcx>,
1066    existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1067) -> Vec<ty::Region<'tcx>> {
1068    let erased_self_ty = tcx.types.trait_object_dummy_self;
1069
1070    let predicates =
1071        existential_predicates.iter().map(|predicate| predicate.with_self_ty(tcx, erased_self_ty));
1072
1073    traits::elaborate(tcx, predicates)
1074        .filter_map(|pred| {
1075            debug!(?pred);
1076            match pred.kind().skip_binder() {
1077                ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ref t, ref r)) => {
1078                    // Search for a bound of the form `erased_self_ty
1079                    // : 'a`, but be wary of something like `for<'a>
1080                    // erased_self_ty : 'a` (we interpret a
1081                    // higher-ranked bound like that as 'static,
1082                    // though at present the code in `fulfill.rs`
1083                    // considers such bounds to be unsatisfiable, so
1084                    // it's kind of a moot point since you could never
1085                    // construct such an object, but this seems
1086                    // correct even if that code changes).
1087                    if t == &erased_self_ty && !r.has_escaping_bound_vars() {
1088                        Some(*r)
1089                    } else {
1090                        None
1091                    }
1092                }
1093                ty::ClauseKind::Trait(_)
1094                | ty::ClauseKind::HostEffect(..)
1095                | ty::ClauseKind::RegionOutlives(_)
1096                | ty::ClauseKind::Projection(_)
1097                | ty::ClauseKind::ConstArgHasType(_, _)
1098                | ty::ClauseKind::WellFormed(_)
1099                | ty::ClauseKind::UnstableFeature(_)
1100                | ty::ClauseKind::ConstEvaluatable(_) => None,
1101            }
1102        })
1103        .collect()
1104}