Skip to main content

rustc_hir_analysis/coherence/
orphan.rs

1//! Orphan checker: every impl either implements a trait defined in this
2//! crate or pertains to a type defined in this crate.
3
4use rustc_data_structures::fx::FxIndexSet;
5use rustc_errors::ErrorGuaranteed;
6use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, TyCtxtInferExt};
7use rustc_lint_defs::builtin::UNCOVERED_PARAM_IN_PROJECTION;
8use rustc_middle::ty::{
9    self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
10    Unnormalized,
11};
12use rustc_middle::{bug, span_bug};
13use rustc_span::def_id::{DefId, LocalDefId};
14use rustc_trait_selection::traits::{
15    self, IsFirstInputType, OrphanCheckErr, OrphanCheckMode, UncoveredTyParams,
16};
17use tracing::{debug, instrument};
18
19use crate::diagnostics;
20
21#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("orphan_check_impl",
                                    "rustc_hir_analysis::coherence::orphan",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/coherence/orphan.rs"),
                                    ::tracing_core::__macro_support::Option::Some(21u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::coherence::orphan"),
                                    ::tracing_core::field::FieldSet::new(&["impl_def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl_def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let trait_ref =
                tcx.impl_trait_ref(impl_def_id).instantiate_identity().skip_norm_wip();
            trait_ref.error_reported()?;
            match orphan_check(tcx, impl_def_id, OrphanCheckMode::Proper) {
                Ok(()) => {}
                Err(err) =>
                    match orphan_check(tcx, impl_def_id,
                            OrphanCheckMode::Compat) {
                        Ok(()) =>
                            match err {
                                OrphanCheckErr::UncoveredTyParams(uncovered_ty_params) => {
                                    let hir_id = tcx.local_def_id_to_hir_id(impl_def_id);
                                    for param_def_id in uncovered_ty_params.uncovered {
                                        let ident = tcx.item_ident(param_def_id);
                                        tcx.emit_node_span_lint(UNCOVERED_PARAM_IN_PROJECTION,
                                            hir_id, ident.span,
                                            diagnostics::UncoveredTyParam {
                                                param: ident,
                                                local_ty: uncovered_ty_params.local_ty,
                                            });
                                    }
                                }
                                OrphanCheckErr::NonLocalInputType(_) => {
                                    ::rustc_middle::util::bug::bug_fmt(format_args!("orphanck: shouldn\'t\'ve gotten non-local input tys in compat mode"))
                                }
                            },
                        Err(err) =>
                            return Err(emit_orphan_check_error(tcx, trait_ref,
                                        impl_def_id, err)),
                    },
            }
            let trait_def_id = trait_ref.def_id;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/coherence/orphan.rs:92",
                                    "rustc_hir_analysis::coherence::orphan",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/coherence/orphan.rs"),
                                    ::tracing_core::__macro_support::Option::Some(92u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::coherence::orphan"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("trait_ref={0:?} trait_def_id={1:?} trait_is_auto={2}",
                                                                trait_ref, trait_def_id, tcx.trait_is_auto(trait_def_id)) as
                                                        &dyn Value))])
                        });
                } else { ; }
            };
            if tcx.trait_is_auto(trait_def_id) {
                let self_ty = tcx.expand_free_alias_tys(trait_ref.self_ty());
                enum LocalImpl {
                    Allow,
                    Disallow {
                        problematic_kind: &'static str,
                    },
                }
                enum NonlocalImpl {
                    Allow,
                    DisallowBecauseNonlocal,
                    DisallowOther,
                }
                let (local_impl, nonlocal_impl) =
                    match self_ty.kind() {
                        ty::Adt(self_def, _) =>
                            (LocalImpl::Allow,
                                if self_def.did().is_local() {
                                    NonlocalImpl::Allow
                                } else { NonlocalImpl::DisallowBecauseNonlocal }),
                        ty::Foreign(did) =>
                            (LocalImpl::Allow,
                                if did.is_local() {
                                    NonlocalImpl::Allow
                                } else { NonlocalImpl::DisallowBecauseNonlocal }),
                        ty::Dynamic(..) =>
                            (LocalImpl::Disallow { problematic_kind: "trait object" },
                                NonlocalImpl::DisallowOther),
                        ty::Param(..) =>
                            (if self_ty.is_sized(tcx,
                                        ty::TypingEnv::non_body_analysis(tcx, impl_def_id)) {
                                    LocalImpl::Allow
                                } else {
                                    LocalImpl::Disallow { problematic_kind: "generic type" }
                                }, NonlocalImpl::DisallowOther),
                        ty::Alias(_, ty::AliasTy { kind, .. }) => {
                            let problematic_kind =
                                match kind {
                                    ty::Projection { .. } => "associated type",
                                    ty::Free { .. } => "type alias",
                                    ty::Opaque { .. } => "opaque type",
                                    ty::Inherent { .. } => "associated type",
                                };
                            (LocalImpl::Disallow { problematic_kind },
                                NonlocalImpl::DisallowOther)
                        }
                        ty::Bool | ty::Pat(..) | ty::Char | ty::Int(..) |
                            ty::Uint(..) | ty::Float(..) | ty::Str | ty::Array(..) |
                            ty::Slice(..) | ty::RawPtr(..) | ty::Ref(..) | ty::FnPtr(..)
                            | ty::Never | ty::Tuple(..) | ty::UnsafeBinder(_) =>
                            (LocalImpl::Allow, NonlocalImpl::DisallowOther),
                        ty::FnDef(..) | ty::Closure(..) | ty::CoroutineClosure(..) |
                            ty::Coroutine(..) | ty::CoroutineWitness(..) | ty::Bound(..)
                            | ty::Placeholder(..) | ty::Infer(..) => {
                            let sp = tcx.def_span(impl_def_id);
                            ::rustc_middle::util::bug::span_bug_fmt(sp,
                                format_args!("weird self type for autotrait impl"))
                        }
                        ty::Error(..) => (LocalImpl::Allow, NonlocalImpl::Allow),
                    };
                if trait_def_id.is_local() {
                    match local_impl {
                        LocalImpl::Allow => {}
                        LocalImpl::Disallow { problematic_kind } => {
                            return Err(tcx.dcx().emit_err(diagnostics::TraitsWithDefaultImpl {
                                            span: tcx.def_span(impl_def_id),
                                            traits: tcx.def_path_str(trait_def_id),
                                            problematic_kind,
                                            self_ty,
                                        }));
                        }
                    }
                } else {
                    match nonlocal_impl {
                        NonlocalImpl::Allow => {}
                        NonlocalImpl::DisallowBecauseNonlocal => {
                            return Err(tcx.dcx().emit_err(diagnostics::CrossCrateTraitsDefined {
                                            span: tcx.def_span(impl_def_id),
                                            traits: tcx.def_path_str(trait_def_id),
                                        }));
                        }
                        NonlocalImpl::DisallowOther => {
                            return Err(tcx.dcx().emit_err(diagnostics::CrossCrateTraits {
                                            span: tcx.def_span(impl_def_id),
                                            traits: tcx.def_path_str(trait_def_id),
                                            self_ty,
                                        }));
                        }
                    }
                }
            }
            Ok(())
        }
    }
}#[instrument(level = "debug", skip(tcx))]
22pub(crate) fn orphan_check_impl(
23    tcx: TyCtxt<'_>,
24    impl_def_id: LocalDefId,
25) -> Result<(), ErrorGuaranteed> {
26    let trait_ref = tcx.impl_trait_ref(impl_def_id).instantiate_identity().skip_norm_wip();
27    trait_ref.error_reported()?;
28
29    match orphan_check(tcx, impl_def_id, OrphanCheckMode::Proper) {
30        Ok(()) => {}
31        Err(err) => match orphan_check(tcx, impl_def_id, OrphanCheckMode::Compat) {
32            Ok(()) => match err {
33                OrphanCheckErr::UncoveredTyParams(uncovered_ty_params) => {
34                    let hir_id = tcx.local_def_id_to_hir_id(impl_def_id);
35
36                    for param_def_id in uncovered_ty_params.uncovered {
37                        let ident = tcx.item_ident(param_def_id);
38
39                        tcx.emit_node_span_lint(
40                            UNCOVERED_PARAM_IN_PROJECTION,
41                            hir_id,
42                            ident.span,
43                            diagnostics::UncoveredTyParam {
44                                param: ident,
45                                local_ty: uncovered_ty_params.local_ty,
46                            },
47                        );
48                    }
49                }
50                OrphanCheckErr::NonLocalInputType(_) => {
51                    bug!("orphanck: shouldn't've gotten non-local input tys in compat mode")
52                }
53            },
54            Err(err) => return Err(emit_orphan_check_error(tcx, trait_ref, impl_def_id, err)),
55        },
56    }
57
58    let trait_def_id = trait_ref.def_id;
59
60    // In addition to the above rules, we restrict impls of auto traits
61    // so that they can only be implemented on nominal types, such as structs,
62    // enums or foreign types. To see why this restriction exists, consider the
63    // following example (#22978). Imagine that crate A defines an auto trait
64    // `Foo` and a fn that operates on pairs of types:
65    //
66    // ```
67    // // Crate A
68    // auto trait Foo { }
69    // fn two_foos<A:Foo,B:Foo>(..) {
70    //     one_foo::<(A,B)>(..)
71    // }
72    // fn one_foo<T:Foo>(..) { .. }
73    // ```
74    //
75    // This type-checks fine; in particular the fn
76    // `two_foos` is able to conclude that `(A,B):Foo`
77    // because `A:Foo` and `B:Foo`.
78    //
79    // Now imagine that crate B comes along and does the following:
80    //
81    // ```
82    // struct A { }
83    // struct B { }
84    // impl Foo for A { }
85    // impl Foo for B { }
86    // impl !Foo for (A, B) { }
87    // ```
88    //
89    // This final impl is legal according to the orphan
90    // rules, but it invalidates the reasoning from
91    // `two_foos` above.
92    debug!(
93        "trait_ref={:?} trait_def_id={:?} trait_is_auto={}",
94        trait_ref,
95        trait_def_id,
96        tcx.trait_is_auto(trait_def_id)
97    );
98
99    if tcx.trait_is_auto(trait_def_id) {
100        // Expand free alias types (e.g. lazy type aliases) so that the checks below operate
101        // on the type the alias resolves to rather than the alias itself. Otherwise an impl
102        // whose self type is an alias expanding to an otherwise valid nominal type would be
103        // wrongly rejected, e.g. `unsafe impl Sync for Alias {}` where `type Alias = Local;`.
104        // Expansion also reveals genuinely problematic self types (trait objects, opaque
105        // types, type parameters), so those keep being rejected. See issue #157756.
106        let self_ty = tcx.expand_free_alias_tys(trait_ref.self_ty());
107
108        // If the impl is in the same crate as the auto-trait, almost anything
109        // goes.
110        //
111        //     impl MyAuto for Rc<Something> {}  // okay
112        //     impl<T> !MyAuto for *const T {}   // okay
113        //     impl<T> MyAuto for T {}           // okay
114        //
115        // But there is one important exception: implementing for a trait object
116        // is not allowed.
117        //
118        //     impl MyAuto for dyn Trait {}      // NOT OKAY
119        //     impl<T: ?Sized> MyAuto for T {}   // NOT OKAY
120        //
121        // With this restriction, it's guaranteed that an auto-trait is
122        // implemented for a trait object if and only if the auto-trait is one
123        // of the trait object's trait bounds (or a supertrait of a bound). In
124        // other words `dyn Trait + AutoTrait` always implements AutoTrait,
125        // while `dyn Trait` never implements AutoTrait.
126        //
127        // This is necessary in order for autotrait bounds on methods of trait
128        // objects to be sound.
129        //
130        //     auto trait AutoTrait {}
131        //
132        //     trait DynCompatibleTrait {
133        //         fn f(&self) where Self: AutoTrait;
134        //     }
135        //
136        // We can allow f to be called on `dyn DynCompatibleTrait + AutoTrait`.
137        //
138        // If we didn't deny `impl AutoTrait for dyn Trait`, it would be unsound
139        // for the `DynCompatibleTrait` shown above to be dyn-compatible because someone
140        // could take some type implementing `DynCompatibleTrait` but not `AutoTrait`,
141        // unsize it to `dyn DynCompatibleTrait`, and call `.f()` which has no
142        // concrete implementation (issue #50781).
143        enum LocalImpl {
144            Allow,
145            Disallow { problematic_kind: &'static str },
146        }
147
148        // If the auto-trait is from a dependency, it must only be getting
149        // implemented for a nominal type, and specifically one local to the
150        // current crate.
151        //
152        //     impl<T> Sync for MyStruct<T> {}   // okay
153        //
154        //     impl Sync for Rc<MyStruct> {}     // NOT OKAY
155        enum NonlocalImpl {
156            Allow,
157            DisallowBecauseNonlocal,
158            DisallowOther,
159        }
160
161        // Exhaustive match considering that this logic is essential for
162        // soundness.
163        let (local_impl, nonlocal_impl) = match self_ty.kind() {
164            // struct Struct<T>;
165            // impl AutoTrait for Struct<Foo> {}
166            ty::Adt(self_def, _) => (
167                LocalImpl::Allow,
168                if self_def.did().is_local() {
169                    NonlocalImpl::Allow
170                } else {
171                    NonlocalImpl::DisallowBecauseNonlocal
172                },
173            ),
174
175            // extern { type OpaqueType; }
176            // impl AutoTrait for OpaqueType {}
177            ty::Foreign(did) => (
178                LocalImpl::Allow,
179                if did.is_local() {
180                    NonlocalImpl::Allow
181                } else {
182                    NonlocalImpl::DisallowBecauseNonlocal
183                },
184            ),
185
186            // impl AutoTrait for dyn Trait {}
187            ty::Dynamic(..) => (
188                LocalImpl::Disallow { problematic_kind: "trait object" },
189                NonlocalImpl::DisallowOther,
190            ),
191
192            // impl<T> AutoTrait for T {}
193            // impl<T: ?Sized> AutoTrait for T {}
194            ty::Param(..) => (
195                if self_ty.is_sized(tcx, ty::TypingEnv::non_body_analysis(tcx, impl_def_id)) {
196                    LocalImpl::Allow
197                } else {
198                    LocalImpl::Disallow { problematic_kind: "generic type" }
199                },
200                NonlocalImpl::DisallowOther,
201            ),
202
203            ty::Alias(_, ty::AliasTy { kind, .. }) => {
204                let problematic_kind = match kind {
205                    // trait Id { type This: ?Sized; }
206                    // impl<T: ?Sized> Id for T {
207                    //     type This = T;
208                    // }
209                    // impl<T: ?Sized> AutoTrait for <T as Id>::This {}
210                    ty::Projection { .. } => "associated type",
211                    // type Foo = (impl Sized, bool)
212                    // impl AutoTrait for Foo {}
213                    ty::Free { .. } => "type alias",
214                    // type Opaque = impl Trait;
215                    // impl AutoTrait for Opaque {}
216                    ty::Opaque { .. } => "opaque type",
217                    // ```
218                    // struct S<T>(T);
219                    // impl<T: ?Sized> S<T> {
220                    //     type This = T;
221                    // }
222                    // impl<T: ?Sized> AutoTrait for S<T>::This {}
223                    // ```
224                    // FIXME(inherent_associated_types): The example code above currently leads to a cycle
225                    ty::Inherent { .. } => "associated type",
226                };
227                (LocalImpl::Disallow { problematic_kind }, NonlocalImpl::DisallowOther)
228            }
229
230            ty::Bool
231            | ty::Pat(..)
232            | ty::Char
233            | ty::Int(..)
234            | ty::Uint(..)
235            | ty::Float(..)
236            | ty::Str
237            | ty::Array(..)
238            | ty::Slice(..)
239            | ty::RawPtr(..)
240            | ty::Ref(..)
241            | ty::FnPtr(..)
242            | ty::Never
243            | ty::Tuple(..)
244            | ty::UnsafeBinder(_) => (LocalImpl::Allow, NonlocalImpl::DisallowOther),
245
246            ty::FnDef(..)
247            | ty::Closure(..)
248            | ty::CoroutineClosure(..)
249            | ty::Coroutine(..)
250            | ty::CoroutineWitness(..)
251            | ty::Bound(..)
252            | ty::Placeholder(..)
253            | ty::Infer(..) => {
254                let sp = tcx.def_span(impl_def_id);
255                span_bug!(sp, "weird self type for autotrait impl")
256            }
257
258            ty::Error(..) => (LocalImpl::Allow, NonlocalImpl::Allow),
259        };
260
261        if trait_def_id.is_local() {
262            match local_impl {
263                LocalImpl::Allow => {}
264                LocalImpl::Disallow { problematic_kind } => {
265                    return Err(tcx.dcx().emit_err(diagnostics::TraitsWithDefaultImpl {
266                        span: tcx.def_span(impl_def_id),
267                        traits: tcx.def_path_str(trait_def_id),
268                        problematic_kind,
269                        self_ty,
270                    }));
271                }
272            }
273        } else {
274            match nonlocal_impl {
275                NonlocalImpl::Allow => {}
276                NonlocalImpl::DisallowBecauseNonlocal => {
277                    return Err(tcx.dcx().emit_err(diagnostics::CrossCrateTraitsDefined {
278                        span: tcx.def_span(impl_def_id),
279                        traits: tcx.def_path_str(trait_def_id),
280                    }));
281                }
282                NonlocalImpl::DisallowOther => {
283                    return Err(tcx.dcx().emit_err(diagnostics::CrossCrateTraits {
284                        span: tcx.def_span(impl_def_id),
285                        traits: tcx.def_path_str(trait_def_id),
286                        self_ty,
287                    }));
288                }
289            }
290        }
291    }
292
293    Ok(())
294}
295
296/// Checks the coherence orphan rules.
297///
298/// `impl_def_id` should be the `DefId` of a trait impl.
299///
300/// To pass, either the trait must be local, or else two conditions must be satisfied:
301///
302/// 1. All type parameters in `Self` must be "covered" by some local type constructor.
303/// 2. Some local type must appear in `Self`.
304x;#[instrument(level = "debug", skip(tcx), ret)]
305fn orphan_check<'tcx>(
306    tcx: TyCtxt<'tcx>,
307    impl_def_id: LocalDefId,
308    mode: OrphanCheckMode,
309) -> Result<(), OrphanCheckErr<TyCtxt<'tcx>, FxIndexSet<DefId>>> {
310    // We only accept this routine to be invoked on implementations
311    // of a trait, not inherent implementations.
312    let trait_ref = tcx.impl_trait_ref(impl_def_id);
313    debug!(trait_ref = ?trait_ref.skip_binder());
314
315    // If the *trait* is local to the crate, ok.
316    if let Some(def_id) = trait_ref.skip_binder().def_id.as_local() {
317        debug!("trait {def_id:?} is local to current crate");
318        return Ok(());
319    }
320
321    // (1)  Instantiate all generic params with fresh inference vars.
322    let infcx = tcx.infer_ctxt().build(TypingMode::Coherence);
323    let cause = traits::ObligationCause::dummy();
324    let args = infcx.fresh_args_for_item(cause.span, impl_def_id.to_def_id());
325    let trait_ref = trait_ref.instantiate(tcx, args).skip_norm_wip();
326
327    let lazily_normalize_ty = |user_ty: Ty<'tcx>| {
328        let ty::Alias(..) = user_ty.kind() else { return Ok(user_ty) };
329
330        let ocx = traits::ObligationCtxt::new(&infcx);
331        let ty = ocx.normalize(&cause, ty::ParamEnv::empty(), Unnormalized::new_wip(user_ty));
332        let ty = infcx.resolve_vars_if_possible(ty);
333        let errors = ocx.try_evaluate_obligations();
334        if !errors.is_empty() {
335            return Ok(user_ty);
336        }
337
338        Ok::<_, !>(ty)
339    };
340
341    let result = traits::orphan_check_trait_ref(
342        &infcx,
343        trait_ref,
344        traits::InCrate::Local { mode },
345        lazily_normalize_ty,
346    )
347    .into_ok();
348
349    // (2)  Try to map the remaining inference vars back to generic params.
350    result.map_err(|err| match err {
351        OrphanCheckErr::UncoveredTyParams(UncoveredTyParams { uncovered, local_ty }) => {
352            let mut collector =
353                UncoveredTyParamCollector { infcx: &infcx, uncovered_params: Default::default() };
354            uncovered.visit_with(&mut collector);
355            // FIXME(fmease): This is very likely reachable.
356            debug_assert!(!collector.uncovered_params.is_empty());
357
358            OrphanCheckErr::UncoveredTyParams(UncoveredTyParams {
359                uncovered: collector.uncovered_params,
360                local_ty,
361            })
362        }
363        OrphanCheckErr::NonLocalInputType(tys) => {
364            let tys = infcx.probe(|_| {
365                // Map the unconstrained args back to their params,
366                // ignoring any type unification errors.
367                for (arg, id_arg) in
368                    std::iter::zip(args, ty::GenericArgs::identity_for_item(tcx, impl_def_id))
369                {
370                    let _ = infcx.at(&cause, ty::ParamEnv::empty()).eq(
371                        DefineOpaqueTypes::No,
372                        arg,
373                        id_arg,
374                    );
375                }
376                infcx.resolve_vars_if_possible(tys)
377            });
378            OrphanCheckErr::NonLocalInputType(tys)
379        }
380    })
381}
382
383fn emit_orphan_check_error<'tcx>(
384    tcx: TyCtxt<'tcx>,
385    trait_ref: ty::TraitRef<'tcx>,
386    impl_def_id: LocalDefId,
387    err: traits::OrphanCheckErr<TyCtxt<'tcx>, FxIndexSet<DefId>>,
388) -> ErrorGuaranteed {
389    match err {
390        traits::OrphanCheckErr::NonLocalInputType(tys) => {
391            let item = tcx.hir_expect_item(impl_def_id);
392            let impl_ = item.expect_impl();
393            let of_trait = impl_.of_trait.unwrap();
394
395            let span = tcx.def_span(impl_def_id);
396            let mut diag = tcx.dcx().create_err(match trait_ref.self_ty().kind() {
397                ty::Adt(..) => diagnostics::OnlyCurrentTraits::Outside { span, note: () },
398                _ if trait_ref.self_ty().is_primitive() => {
399                    diagnostics::OnlyCurrentTraits::Primitive { span, note: () }
400                }
401                _ => diagnostics::OnlyCurrentTraits::Arbitrary { span, note: () },
402            });
403
404            for &(mut ty, is_target_ty) in &tys {
405                let span = if #[allow(non_exhaustive_omitted_patterns)] match is_target_ty {
    IsFirstInputType::Yes => true,
    _ => false,
}matches!(is_target_ty, IsFirstInputType::Yes) {
406                    // Point at `D<A>` in `impl<A, B> for C<B> in D<A>`
407                    impl_.self_ty.span
408                } else {
409                    // Point at `C<B>` in `impl<A, B> for C<B> in D<A>`
410                    of_trait.trait_ref.path.span
411                };
412
413                ty = tcx.erase_and_anonymize_regions(ty);
414
415                let is_foreign =
416                    !trait_ref.def_id.is_local() && #[allow(non_exhaustive_omitted_patterns)] match is_target_ty {
    IsFirstInputType::No => true,
    _ => false,
}matches!(is_target_ty, IsFirstInputType::No);
417
418                match *ty.kind() {
419                    ty::Slice(_) => {
420                        if is_foreign {
421                            diag.subdiagnostic(diagnostics::OnlyCurrentTraitsForeign { span });
422                        } else {
423                            diag.subdiagnostic(diagnostics::OnlyCurrentTraitsName {
424                                span,
425                                name: "slices",
426                            });
427                        }
428                    }
429                    ty::Array(..) => {
430                        if is_foreign {
431                            diag.subdiagnostic(diagnostics::OnlyCurrentTraitsForeign { span });
432                        } else {
433                            diag.subdiagnostic(diagnostics::OnlyCurrentTraitsName {
434                                span,
435                                name: "arrays",
436                            });
437                        }
438                    }
439                    ty::Tuple(..) => {
440                        if is_foreign {
441                            diag.subdiagnostic(diagnostics::OnlyCurrentTraitsForeign { span });
442                        } else {
443                            diag.subdiagnostic(diagnostics::OnlyCurrentTraitsName {
444                                span,
445                                name: "tuples",
446                            });
447                        }
448                    }
449                    ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => {
450                        diag.subdiagnostic(diagnostics::OnlyCurrentTraitsOpaque { span });
451                    }
452                    ty::RawPtr(ptr_ty, mutbl) => {
453                        if !trait_ref.self_ty().has_param() {
454                            diag.subdiagnostic(diagnostics::OnlyCurrentTraitsPointerSugg {
455                                wrapper_span: impl_.self_ty.span,
456                                struct_span: item.span.shrink_to_lo(),
457                                mut_key: mutbl.prefix_str(),
458                                ptr_ty,
459                            });
460                        }
461                        diag.subdiagnostic(diagnostics::OnlyCurrentTraitsPointer {
462                            span,
463                            pointer: ty,
464                        });
465                    }
466                    ty::Adt(adt_def, _) => {
467                        diag.subdiagnostic(diagnostics::OnlyCurrentTraitsAdt {
468                            span,
469                            name: tcx.def_path_str(adt_def.did()),
470                        });
471                    }
472                    _ => {
473                        diag.subdiagnostic(diagnostics::OnlyCurrentTraitsTy { span, ty });
474                    }
475                }
476            }
477
478            diag.emit()
479        }
480        traits::OrphanCheckErr::UncoveredTyParams(UncoveredTyParams { uncovered, local_ty }) => {
481            let mut guar = None;
482            for param_def_id in uncovered {
483                guar.get_or_insert(tcx.dcx().emit_err(diagnostics::UncoveredTyParam {
484                    param: tcx.item_ident(param_def_id),
485                    local_ty,
486                }));
487            }
488            guar.unwrap()
489        }
490    }
491}
492
493struct UncoveredTyParamCollector<'cx, 'tcx> {
494    infcx: &'cx InferCtxt<'tcx>,
495    uncovered_params: FxIndexSet<DefId>,
496}
497
498impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for UncoveredTyParamCollector<'_, 'tcx> {
499    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
500        if !ty.has_type_flags(ty::TypeFlags::HAS_TY_INFER) {
501            return;
502        }
503        let ty::Infer(ty::TyVar(vid)) = *ty.kind() else {
504            return ty.super_visit_with(self);
505        };
506        let origin = self.infcx.type_var_origin(vid);
507        if let Some(def_id) = origin.param_def_id {
508            self.uncovered_params.insert(def_id);
509        }
510    }
511
512    fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
513        if ct.has_type_flags(ty::TypeFlags::HAS_TY_INFER) {
514            ct.super_visit_with(self)
515        }
516    }
517}