Skip to main content

rustc_hir_analysis/impl_wf_check/
min_specialization.rs

1//! # Minimal Specialization
2//!
3//! This module contains the checks for sound specialization used when the
4//! `min_specialization` feature is enabled. This requires that the impl is
5//! *always applicable*.
6//!
7//! If `impl1` specializes `impl2` then `impl1` is always applicable if we know
8//! that all the bounds of `impl2` are satisfied, and all of the bounds of
9//! `impl1` are satisfied for some choice of lifetimes then we know that
10//! `impl1` applies for any choice of lifetimes.
11//!
12//! ## Basic approach
13//!
14//! To enforce this requirement on specializations we take the following
15//! approach:
16//!
17//! 1. Match up the args for `impl2` so that the implemented trait and
18//!    self-type match those for `impl1`.
19//! 2. Check for any direct use of `'static` in the args of `impl2`.
20//! 3. Check that all of the generic parameters of `impl1` occur at most once
21//!    in the *unconstrained* args for `impl2`. A parameter is constrained if
22//!    its value is completely determined by an associated type projection
23//!    predicate.
24//! 4. Check that all predicates on `impl1` either exist on `impl2` (after
25//!    matching args), or are well-formed predicates for the trait's type
26//!    arguments.
27//!
28//! ## Example
29//!
30//! Suppose we have the following always applicable impl:
31//!
32//! ```ignore (illustrative)
33//! impl<T> SpecExtend<T> for std::vec::IntoIter<T> { /* specialized impl */ }
34//! impl<T, I: Iterator<Item=T>> SpecExtend<T> for I { /* default impl */ }
35//! ```
36//!
37//! We get that the generic parameters for `impl2` are `[T, std::vec::IntoIter<T>]`.
38//! `T` is constrained to be `<I as Iterator>::Item`, so we check only
39//! `std::vec::IntoIter<T>` for repeated parameters, which it doesn't have. The
40//! predicates of `impl1` are only `T: Sized`, which is also a predicate of
41//! `impl2`. So this specialization is sound.
42//!
43//! ## Extensions
44//!
45//! Unfortunately not all specializations in the standard library are allowed
46//! by this. So there are two extensions to these rules that allow specializing
47//! on some traits: that is, using them as bounds on the specializing impl,
48//! even when they don't occur in the base impl.
49//!
50//! ### rustc_specialization_trait
51//!
52//! If a trait is always applicable, then it's sound to specialize on it. We
53//! check trait is always applicable in the same way as impls, except that step
54//! 4 is now "all predicates on `impl1` are always applicable". We require that
55//! `specialization` or `min_specialization` is enabled to implement these
56//! traits.
57//!
58//! ### rustc_unsafe_specialization_marker
59//!
60//! There are also some specialization on traits with no methods, including the
61//! stable `FusedIterator` trait. We allow marking marker traits with an
62//! unstable attribute that means we ignore them in point 3 of the checks
63//! above. This is unsound, in the sense that the specialized impl may be used
64//! when it doesn't apply, but we allow it in the short term since it can't
65//! cause use after frees with purely safe code in the same way as specializing
66//! on traits with methods can.
67
68use rustc_data_structures::fx::FxHashSet;
69use rustc_hir::def_id::{DefId, LocalDefId};
70use rustc_infer::infer::TyCtxtInferExt;
71use rustc_infer::traits::ObligationCause;
72use rustc_infer::traits::specialization_graph::Node;
73use rustc_middle::ty::trait_def::TraitSpecializationKind;
74use rustc_middle::ty::{
75    self, GenericArg, GenericArgs, GenericArgsRef, RegionUtilitiesExt, TyCtxt, TypeVisitableExt,
76    TypingMode,
77};
78use rustc_span::{ErrorGuaranteed, Span};
79use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
80use rustc_trait_selection::traits::{self, ObligationCtxt, translate_args_with_cause, wf};
81use tracing::{debug, instrument};
82
83use crate::diagnostics::GenericArgsOnOverriddenImpl;
84use crate::{constrained_generic_params as cgp, diagnostics};
85
86pub(super) fn check_min_specialization(
87    tcx: TyCtxt<'_>,
88    impl_def_id: LocalDefId,
89) -> Result<(), ErrorGuaranteed> {
90    if let Some(node) = parent_specialization_node(tcx, impl_def_id) {
91        check_always_applicable(tcx, impl_def_id, node)?;
92    }
93    Ok(())
94}
95
96fn parent_specialization_node(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId) -> Option<Node> {
97    let trait_ref = tcx.impl_trait_ref(impl1_def_id);
98    let trait_def = tcx.trait_def(trait_ref.skip_binder().def_id);
99
100    let impl2_node = trait_def.ancestors(tcx, impl1_def_id.to_def_id()).ok()?.nth(1)?;
101
102    let always_applicable_trait =
103        #[allow(non_exhaustive_omitted_patterns)] match trait_def.specialization_kind
    {
    TraitSpecializationKind::AlwaysApplicable => true,
    _ => false,
}matches!(trait_def.specialization_kind, TraitSpecializationKind::AlwaysApplicable);
104    if impl2_node.is_from_trait() && !always_applicable_trait {
105        // Implementing a normal trait isn't a specialization.
106        return None;
107    }
108    if trait_def.is_marker {
109        // Overlapping marker implementations are not really specializations.
110        return None;
111    }
112    Some(impl2_node)
113}
114
115/// Check that `impl1` is a sound specialization
116#[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("check_always_applicable",
                                    "rustc_hir_analysis::impl_wf_check::min_specialization",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs"),
                                    ::tracing_core::__macro_support::Option::Some(116u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::impl_wf_check::min_specialization"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl1_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl1_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl2_node")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl2_node");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl1_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl2_node)
                                                            as &dyn ::tracing::field::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 span = tcx.def_span(impl1_def_id);
            let (impl1_args, impl2_args) =
                get_impl_args(tcx, impl1_def_id, impl2_node)?;
            let impl2_def_id = impl2_node.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/impl_wf_check/min_specialization.rs:126",
                                    "rustc_hir_analysis::impl_wf_check::min_specialization",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs"),
                                    ::tracing_core::__macro_support::Option::Some(126u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::impl_wf_check::min_specialization"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl2_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl2_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl2_args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl2_args");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl2_def_id)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl2_args)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let parent_args =
                if impl2_node.is_from_trait() {
                    impl2_args.to_vec()
                } else {
                    unconstrained_parent_impl_args(tcx, impl2_def_id,
                        impl2_args)
                };
            check_has_items(tcx, impl1_def_id, impl2_node,
                            span).and(check_static_lifetimes(tcx, &parent_args,
                            span)).and(check_duplicate_params(tcx, impl1_args,
                        parent_args,
                        span)).and(check_predicates(tcx, impl1_def_id, impl1_args,
                    impl2_node, impl2_args, span))
        }
    }
}#[instrument(level = "debug", skip(tcx))]
117fn check_always_applicable(
118    tcx: TyCtxt<'_>,
119    impl1_def_id: LocalDefId,
120    impl2_node: Node,
121) -> Result<(), ErrorGuaranteed> {
122    let span = tcx.def_span(impl1_def_id);
123
124    let (impl1_args, impl2_args) = get_impl_args(tcx, impl1_def_id, impl2_node)?;
125    let impl2_def_id = impl2_node.def_id();
126    debug!(?impl2_def_id, ?impl2_args);
127
128    let parent_args = if impl2_node.is_from_trait() {
129        impl2_args.to_vec()
130    } else {
131        unconstrained_parent_impl_args(tcx, impl2_def_id, impl2_args)
132    };
133
134    check_has_items(tcx, impl1_def_id, impl2_node, span)
135        .and(check_static_lifetimes(tcx, &parent_args, span))
136        .and(check_duplicate_params(tcx, impl1_args, parent_args, span))
137        .and(check_predicates(tcx, impl1_def_id, impl1_args, impl2_node, impl2_args, span))
138}
139
140fn check_has_items(
141    tcx: TyCtxt<'_>,
142    impl1_def_id: LocalDefId,
143    impl2_node: Node,
144    span: Span,
145) -> Result<(), ErrorGuaranteed> {
146    if let Node::Impl(impl2_id) = impl2_node
147        && tcx.associated_item_def_ids(impl1_def_id).is_empty()
148    {
149        let base_impl_span = tcx.def_span(impl2_id);
150        return Err(tcx.dcx().emit_err(diagnostics::EmptySpecialization { span, base_impl_span }));
151    }
152    Ok(())
153}
154
155/// Given a specializing impl `impl1`, and the base impl `impl2`, returns two
156/// generic parameters `(S1, S2)` that equate their trait references.
157/// The returned types are expressed in terms of the generics of `impl1`.
158///
159/// Example
160///
161/// ```ignore (illustrative)
162/// impl<A, B> Foo<A> for B { /* impl2 */ }
163/// impl<C> Foo<Vec<C>> for C { /* impl1 */ }
164/// ```
165///
166/// Would return `S1 = [C]` and `S2 = [Vec<C>, C]`.
167fn get_impl_args(
168    tcx: TyCtxt<'_>,
169    impl1_def_id: LocalDefId,
170    impl2_node: Node,
171) -> Result<(GenericArgsRef<'_>, GenericArgsRef<'_>), ErrorGuaranteed> {
172    let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
173    let ocx = ObligationCtxt::new_with_diagnostics(infcx);
174    let param_env = tcx.param_env(impl1_def_id);
175    let impl1_span = tcx.def_span(impl1_def_id);
176
177    let impl1_args = GenericArgs::identity_for_item(tcx, impl1_def_id);
178    let impl2_args = translate_args_with_cause(
179        infcx,
180        param_env,
181        impl1_def_id.to_def_id(),
182        impl1_args,
183        impl2_node,
184        &ObligationCause::misc(impl1_span, impl1_def_id),
185    );
186
187    let errors = ocx.evaluate_obligations_error_on_ambiguity();
188    if !errors.is_empty() {
189        let guar = ocx.infcx.err_ctxt().report_fulfillment_errors(errors);
190        return Err(guar);
191    }
192
193    let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl1_def_id)?;
194    ocx.resolve_regions_and_report_errors(impl1_def_id, param_env, assumed_wf_types)?;
195    let Ok(impl2_args) = infcx.fully_resolve(impl2_args) else {
196        let span = tcx.def_span(impl1_def_id);
197        let guar = tcx.dcx().emit_err(GenericArgsOnOverriddenImpl { span });
198        return Err(guar);
199    };
200    Ok((impl1_args, impl2_args))
201}
202
203/// Returns a list of all of the unconstrained generic parameters of the given impl.
204///
205/// For example given the impl:
206///
207/// impl<'a, T, I> ... where &'a I: IntoIterator<Item=&'a T>
208///
209/// This would return the args corresponding to `['a, I]`, because knowing
210/// `'a` and `I` determines the value of `T`.
211fn unconstrained_parent_impl_args<'tcx>(
212    tcx: TyCtxt<'tcx>,
213    impl_def_id: DefId,
214    impl_args: GenericArgsRef<'tcx>,
215) -> Vec<GenericArg<'tcx>> {
216    let impl_generic_predicates = tcx.predicates_of(impl_def_id);
217    let mut unconstrained_parameters = FxHashSet::default();
218    let mut constrained_params = FxHashSet::default();
219    let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).instantiate_identity().skip_norm_wip();
220
221    // Unfortunately the functions in `constrained_generic_parameters` don't do
222    // what we want here. We want only a list of constrained parameters while
223    // the functions in `cgp` add the constrained parameters to a list of
224    // unconstrained parameters.
225    for (clause, _) in impl_generic_predicates.predicates.iter() {
226        if let ty::ClauseKind::Projection(proj) = clause.kind().skip_binder() {
227            let unbound_trait_ref = proj.projection_term.trait_ref(tcx);
228            if unbound_trait_ref == impl_trait_ref {
229                continue;
230            }
231
232            unconstrained_parameters.extend(cgp::parameters_for(tcx, proj.projection_term, true));
233
234            for param in cgp::parameters_for(tcx, proj.term, false) {
235                if !unconstrained_parameters.contains(&param) {
236                    constrained_params.insert(param.0);
237                }
238            }
239
240            unconstrained_parameters.extend(cgp::parameters_for(tcx, proj.term, true));
241        }
242    }
243
244    impl_args
245        .iter()
246        .enumerate()
247        .filter(|&(idx, _)| !constrained_params.contains(&(idx as u32)))
248        .map(|(_, arg)| arg)
249        .collect()
250}
251
252/// Check that parameters of the derived impl don't occur more than once in the
253/// equated args of the base impl.
254///
255/// For example forbid the following:
256///
257/// ```ignore (illustrative)
258/// impl<A> Tr for A { }
259/// impl<B> Tr for (B, B) { }
260/// ```
261///
262/// Note that only consider the unconstrained parameters of the base impl:
263///
264/// ```ignore (illustrative)
265/// impl<S, I: IntoIterator<Item = S>> Tr<S> for I { }
266/// impl<T> Tr<T> for Vec<T> { }
267/// ```
268///
269/// The args for the parent impl here are `[T, Vec<T>]`, which repeats `T`,
270/// but `S` is constrained in the parent impl, so `parent_args` is only
271/// `[Vec<T>]`. This means we allow this impl.
272fn check_duplicate_params<'tcx>(
273    tcx: TyCtxt<'tcx>,
274    impl1_args: GenericArgsRef<'tcx>,
275    parent_args: Vec<GenericArg<'tcx>>,
276    span: Span,
277) -> Result<(), ErrorGuaranteed> {
278    let mut base_params = cgp::parameters_for(tcx, parent_args, true);
279    base_params.sort_unstable();
280    if let (_, [duplicate, ..]) = base_params.partition_dedup() {
281        let param = impl1_args[duplicate.0 as usize];
282        return Err(tcx
283            .dcx()
284            .struct_span_err(span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("specializing impl repeats parameter `{0}`",
                param))
    })format!("specializing impl repeats parameter `{param}`"))
285            .emit());
286    }
287    Ok(())
288}
289
290/// Check that `'static` lifetimes are not introduced by the specializing impl.
291///
292/// For example forbid the following:
293///
294/// ```ignore (illustrative)
295/// impl<A> Tr for A { }
296/// impl Tr for &'static i32 { }
297/// ```
298fn check_static_lifetimes<'tcx>(
299    tcx: TyCtxt<'tcx>,
300    parent_args: &Vec<GenericArg<'tcx>>,
301    span: Span,
302) -> Result<(), ErrorGuaranteed> {
303    if tcx.any_free_region_meets(parent_args, |r| r.is_static()) {
304        return Err(tcx.dcx().emit_err(diagnostics::StaticSpecialize { span }));
305    }
306    Ok(())
307}
308
309/// Check whether predicates on the specializing impl (`impl1`) are allowed.
310///
311/// Each predicate `P` must be one of:
312///
313/// * Global (not reference any parameters).
314/// * A `T: Tr` predicate where `Tr` is an always-applicable trait.
315/// * Present on the base impl `impl2`.
316///     * This check is done using the `trait_predicates_eq` function below.
317/// * A well-formed predicate of a type argument of the trait being implemented,
318///   including the `Self`-type.
319#[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("check_predicates",
                                    "rustc_hir_analysis::impl_wf_check::min_specialization",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs"),
                                    ::tracing_core::__macro_support::Option::Some(319u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::impl_wf_check::min_specialization"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl1_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl1_def_id");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl1_args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl1_args");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl2_node")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl2_node");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl2_args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl2_args");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl1_def_id)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl1_args)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl2_node)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl2_args)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::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 impl1_clauses: Vec<(ty::Clause<'_>, _)> =
                traits::elaborate(tcx,
                        tcx.predicates_of(impl1_def_id).instantiate(tcx,
                                    impl1_args).into_iter().map(|(c, s)|
                                (c.skip_norm_wip(), s))).collect();
            let mut impl2_clauses: Vec<ty::Clause<'_>> =
                if impl2_node.is_from_trait() {
                    Vec::new()
                } else {
                    traits::elaborate(tcx,
                            tcx.predicates_of(impl2_node.def_id()).instantiate(tcx,
                                        impl2_args).into_iter().map(|(c, _s)|
                                    c.skip_norm_wip())).collect()
                };
            {
                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/impl_wf_check/min_specialization.rs:351",
                                    "rustc_hir_analysis::impl_wf_check::min_specialization",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs"),
                                    ::tracing_core::__macro_support::Option::Some(351u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::impl_wf_check::min_specialization"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl1_clauses")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl1_clauses");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("impl2_clauses")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("impl2_clauses");
                                                        NAME.as_str()
                                                    }], ::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};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl1_clauses)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&impl2_clauses)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let always_applicable_traits =
                impl1_clauses.iter().copied().filter(|&(clause, _span)|
                            {

                                #[allow(non_exhaustive_omitted_patterns)]
                                match trait_specialization_kind(tcx, clause) {
                                    Some(TraitSpecializationKind::AlwaysApplicable) => true,
                                    _ => false,
                                }
                            }).map(|(c, _span)| c);
            for arg in
                tcx.impl_trait_ref(impl1_def_id).instantiate_identity().skip_norm_wip().args
                {
                let Some(term) = arg.as_term() else { continue; };
                let infcx =
                    &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
                let obligations =
                    wf::obligations(infcx, tcx.param_env(impl1_def_id),
                            impl1_def_id, 0, term, span).unwrap();
                if !!obligations.has_infer() {
                    ::core::panicking::panic("assertion failed: !obligations.has_infer()")
                };
                impl2_clauses.extend(traits::elaborate(tcx,
                            obligations).filter_map(|obligation|
                            obligation.predicate.as_clause()))
            }
            impl2_clauses.extend(traits::elaborate(tcx,
                    always_applicable_traits));
            let mut res = Ok(());
            for (clause1, span) in impl1_clauses {
                if !impl2_clauses.iter().any(|&clause2| clause1 == clause2) {
                    res = res.and(check_specialization_on(tcx, clause1, span))
                }
            }
            res
        }
    }
}#[instrument(level = "debug", skip(tcx))]
320fn check_predicates<'tcx>(
321    tcx: TyCtxt<'tcx>,
322    impl1_def_id: LocalDefId,
323    impl1_args: GenericArgsRef<'tcx>,
324    impl2_node: Node,
325    impl2_args: GenericArgsRef<'tcx>,
326    span: Span,
327) -> Result<(), ErrorGuaranteed> {
328    let impl1_clauses: Vec<(ty::Clause<'_>, _)> = traits::elaborate(
329        tcx,
330        tcx.predicates_of(impl1_def_id)
331            .instantiate(tcx, impl1_args)
332            .into_iter()
333            .map(|(c, s)| (c.skip_norm_wip(), s)),
334    )
335    .collect();
336
337    let mut impl2_clauses: Vec<ty::Clause<'_>> = if impl2_node.is_from_trait() {
338        // Always applicable traits have to be always applicable without any
339        // assumptions.
340        Vec::new()
341    } else {
342        traits::elaborate(
343            tcx,
344            tcx.predicates_of(impl2_node.def_id())
345                .instantiate(tcx, impl2_args)
346                .into_iter()
347                .map(|(c, _s)| c.skip_norm_wip()),
348        )
349        .collect()
350    };
351    debug!(?impl1_clauses, ?impl2_clauses);
352
353    // Since impls of always applicable traits don't get to assume anything, we
354    // can also assume their supertraits apply.
355    //
356    // For example, we allow:
357    //
358    // #[rustc_specialization_trait]
359    // trait AlwaysApplicable: Debug { }
360    //
361    // impl<T> Tr for T { }
362    // impl<T: AlwaysApplicable> Tr for T { }
363    //
364    // Specializing on `AlwaysApplicable` allows also specializing on `Debug`
365    // which is sound because we forbid impls like the following
366    //
367    // impl<D: Debug> AlwaysApplicable for D { }
368    let always_applicable_traits = impl1_clauses
369        .iter()
370        .copied()
371        .filter(|&(clause, _span)| {
372            matches!(
373                trait_specialization_kind(tcx, clause),
374                Some(TraitSpecializationKind::AlwaysApplicable)
375            )
376        })
377        .map(|(c, _span)| c);
378
379    // Include the well-formed predicates of the type parameters of the impl.
380    for arg in tcx.impl_trait_ref(impl1_def_id).instantiate_identity().skip_norm_wip().args {
381        let Some(term) = arg.as_term() else {
382            continue;
383        };
384        let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
385        let obligations =
386            wf::obligations(infcx, tcx.param_env(impl1_def_id), impl1_def_id, 0, term, span)
387                .unwrap();
388
389        assert!(!obligations.has_infer());
390        impl2_clauses.extend(
391            traits::elaborate(tcx, obligations)
392                .filter_map(|obligation| obligation.predicate.as_clause()),
393        )
394    }
395    impl2_clauses.extend(traits::elaborate(tcx, always_applicable_traits));
396
397    let mut res = Ok(());
398    for (clause1, span) in impl1_clauses {
399        if !impl2_clauses.iter().any(|&clause2| clause1 == clause2) {
400            res = res.and(check_specialization_on(tcx, clause1, span))
401        }
402    }
403    res
404}
405
406#[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("check_specialization_on",
                                    "rustc_hir_analysis::impl_wf_check::min_specialization",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs"),
                                    ::tracing_core::__macro_support::Option::Some(406u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::impl_wf_check::min_specialization"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("clause")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("clause");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::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};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&clause)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::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;
        }
        {
            match clause.kind().skip_binder() {
                _ if clause.is_global() => Ok(()),
                ty::ClauseKind::Trait(ty::TraitPredicate {
                    trait_ref, polarity: _ }) => {
                    if #[allow(non_exhaustive_omitted_patterns)] match trait_specialization_kind(tcx,
                                clause) {
                            Some(TraitSpecializationKind::Marker) => true,
                            _ => false,
                        } {
                        Ok(())
                    } else {
                        Err(tcx.dcx().struct_span_err(span,
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("cannot specialize on trait `{0}`",
                                                    tcx.def_path_str(trait_ref.def_id)))
                                        })).emit())
                    }
                }
                ty::ClauseKind::Projection(ty::ProjectionPredicate {
                    projection_term, term }) =>
                    Err(tcx.dcx().struct_span_err(span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("cannot specialize on associated type `{0} == {1}`",
                                                projection_term, term))
                                    })).emit()),
                ty::ClauseKind::ConstArgHasType(..) => { Ok(()) }
                _ =>
                    Err(tcx.dcx().struct_span_err(span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("cannot specialize on predicate `{0}`",
                                                clause))
                                    })).emit()),
            }
        }
    }
}#[instrument(level = "debug", skip(tcx))]
407fn check_specialization_on<'tcx>(
408    tcx: TyCtxt<'tcx>,
409    clause: ty::Clause<'tcx>,
410    span: Span,
411) -> Result<(), ErrorGuaranteed> {
412    match clause.kind().skip_binder() {
413        // Global predicates are either always true or always false, so we
414        // are fine to specialize on.
415        _ if clause.is_global() => Ok(()),
416        // We allow specializing on explicitly marked traits with no associated
417        // items.
418        ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity: _ }) => {
419            if matches!(
420                trait_specialization_kind(tcx, clause),
421                Some(TraitSpecializationKind::Marker)
422            ) {
423                Ok(())
424            } else {
425                Err(tcx
426                    .dcx()
427                    .struct_span_err(
428                        span,
429                        format!(
430                            "cannot specialize on trait `{}`",
431                            tcx.def_path_str(trait_ref.def_id),
432                        ),
433                    )
434                    .emit())
435            }
436        }
437        ty::ClauseKind::Projection(ty::ProjectionPredicate { projection_term, term }) => Err(tcx
438            .dcx()
439            .struct_span_err(
440                span,
441                format!("cannot specialize on associated type `{projection_term} == {term}`",),
442            )
443            .emit()),
444        ty::ClauseKind::ConstArgHasType(..) => {
445            // FIXME(min_specialization), FIXME(const_generics):
446            // It probably isn't right to allow _every_ `ConstArgHasType` but I am somewhat unsure
447            // about the actual rules that would be sound. Can't just always error here because otherwise
448            // std/core doesn't even compile as they have `const N: usize` in some specializing impls.
449            //
450            // While we do not support constructs like `<T, const N: T>` there is probably no risk of
451            // soundness bugs, but when we support generic const parameter types this will need to be
452            // revisited.
453            Ok(())
454        }
455        _ => Err(tcx
456            .dcx()
457            .struct_span_err(span, format!("cannot specialize on predicate `{clause}`"))
458            .emit()),
459    }
460}
461
462fn trait_specialization_kind<'tcx>(
463    tcx: TyCtxt<'tcx>,
464    clause: ty::Clause<'tcx>,
465) -> Option<TraitSpecializationKind> {
466    match clause.kind().skip_binder() {
467        ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity: _ }) => {
468            Some(tcx.trait_def(trait_ref.def_id).specialization_kind)
469        }
470        ty::ClauseKind::RegionOutlives(_)
471        | ty::ClauseKind::TypeOutlives(_)
472        | ty::ClauseKind::Projection(_)
473        | ty::ClauseKind::ConstArgHasType(..)
474        | ty::ClauseKind::WellFormed(_)
475        | ty::ClauseKind::ConstEvaluatable(..)
476        | ty::ClauseKind::UnstableFeature(_)
477        | ty::ClauseKind::HostEffect(..) => None,
478    }
479}