Skip to main content

rustc_passes/
stability.rs

1//! A pass that annotates every item and method with its stability level,
2//! propagating default levels lexically from parent to children ast nodes.
3
4use std::num::NonZero;
5
6use rustc_ast_lowering::stability::extern_abi_stability;
7use rustc_data_structures::fx::FxIndexMap;
8use rustc_data_structures::unord::{ExtendUnord, UnordMap, UnordSet};
9use rustc_feature::{EnabledLangFeature, EnabledLibFeature, UNSTABLE_LANG_FEATURES};
10use rustc_hir::attrs::{AttributeKind, DeprecatedSince};
11use rustc_hir::def::{DefKind, Res};
12use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId, LocalModId};
13use rustc_hir::intravisit::{self, Visitor, VisitorExt};
14use rustc_hir::{
15    self as hir, AmbigArg, ConstStability, Constness, DefaultBodyStability, FieldDef, HirId, Item,
16    ItemKind, Path, Stability, StabilityLevel, StableSince, TraitRef, Ty, TyKind, UnstableReason,
17    UsePath, VERSION_PLACEHOLDER, Variant, find_attr,
18};
19use rustc_lint_defs as lint;
20use rustc_lint_defs::builtin::{
21    DEPRECATED, DUPLICATE_FEATURES, INEFFECTIVE_UNSTABLE_TRAIT_IMPL, STABLE_FEATURES,
22};
23use rustc_middle::hir::nested_filter;
24use rustc_middle::middle::lib_features::{FeatureStability, LibFeatures};
25use rustc_middle::middle::privacy::EffectiveVisibilities;
26use rustc_middle::middle::stability::{AllowUnstable, Deprecated, DeprecationEntry, EvalResult};
27use rustc_middle::query::{LocalCrate, Providers};
28use rustc_middle::ty::print::with_no_trimmed_paths;
29use rustc_middle::ty::{AssocContainer, TyCtxt};
30use rustc_span::{Span, Symbol, sym};
31use tracing::instrument;
32
33use crate::diagnostics;
34
35#[derive(#[automatically_derived]
impl ::core::marker::StructuralPartialEq for AnnotationKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for AnnotationKind {
    #[inline]
    fn eq(&self, other: &AnnotationKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
36enum AnnotationKind {
37    /// Annotation is required if not inherited from unstable parents.
38    Required,
39    /// Annotation is useless, reject it.
40    Prohibited,
41    /// Deprecation annotation is useless, reject it. (Stability attribute is still required.)
42    DeprecationProhibited,
43    /// Annotation itself is useless, but it can be propagated to children.
44    Container,
45}
46
47fn inherit_deprecation(def_kind: DefKind) -> bool {
48    match def_kind {
49        DefKind::LifetimeParam | DefKind::TyParam | DefKind::ConstParam => false,
50        _ => true,
51    }
52}
53
54fn inherit_const_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
55    let def_kind = tcx.def_kind(def_id);
56    match def_kind {
57        DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst { .. } => {
58            match tcx.def_kind(tcx.local_parent(def_id)) {
59                DefKind::Trait | DefKind::Impl { .. } => true,
60                _ => false,
61            }
62        }
63        DefKind::Closure => true,
64        _ => false,
65    }
66}
67
68fn annotation_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> AnnotationKind {
69    let def_kind = tcx.def_kind(def_id);
70    match def_kind {
71        // Inherent impls and foreign modules serve only as containers for other items,
72        // they don't have their own stability. They still can be annotated as unstable
73        // and propagate this unstability to children, but this annotation is completely
74        // optional. They inherit stability from their parents when unannotated.
75        DefKind::Impl { of_trait: false } | DefKind::ForeignMod => AnnotationKind::Container,
76        DefKind::Impl { of_trait: true } => AnnotationKind::DeprecationProhibited,
77
78        // Allow stability attributes on default generic arguments.
79        DefKind::TyParam | DefKind::ConstParam => {
80            match &tcx.hir_node_by_def_id(def_id).expect_generic_param().kind {
81                hir::GenericParamKind::Type { default: Some(_), .. }
82                | hir::GenericParamKind::Const { default: Some(_), .. } => {
83                    AnnotationKind::Container
84                }
85                _ => AnnotationKind::Prohibited,
86            }
87        }
88
89        // Impl items in trait impls cannot have stability.
90        DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst { .. } => {
91            match tcx.def_kind(tcx.local_parent(def_id)) {
92                DefKind::Impl { of_trait: true } => AnnotationKind::Prohibited,
93                _ => AnnotationKind::Required,
94            }
95        }
96
97        _ => AnnotationKind::Required,
98    }
99}
100
101fn lookup_deprecation_entry(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<DeprecationEntry> {
102    let depr = {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(Deprecated {
                        deprecation, span: _ }) => {
                        break 'done Some(*deprecation);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, def_id,
103        Deprecated { deprecation, span: _ } => *deprecation
104    );
105
106    let Some(depr) = depr else {
107        if inherit_deprecation(tcx.def_kind(def_id)) {
108            let parent_id = tcx.opt_local_parent(def_id)?;
109            let parent_depr = tcx.lookup_deprecation_entry(parent_id)?;
110            return Some(parent_depr);
111        }
112
113        return None;
114    };
115
116    // `Deprecation` is just two pointers, no need to intern it
117    Some(DeprecationEntry::local(depr, def_id))
118}
119
120fn inherit_stability(def_kind: DefKind) -> bool {
121    match def_kind {
122        DefKind::Field | DefKind::Variant | DefKind::Ctor(..) => true,
123        _ => false,
124    }
125}
126
127/// If the `-Z force-unstable-if-unmarked` flag is passed then we provide
128/// a parent stability annotation which indicates that this is private
129/// with the `rustc_private` feature. This is intended for use when
130/// compiling library and `rustc_*` crates themselves so we can leverage crates.io
131/// while maintaining the invariant that all sysroot crates are unstable
132/// by default and are unable to be used.
133const FORCE_UNSTABLE: Stability = Stability {
134    level: StabilityLevel::Unstable {
135        reason: UnstableReason::Default,
136        issue: NonZero::new(27812),
137        implied_by: None,
138        old_name: None,
139    },
140    feature: sym::rustc_private,
141};
142
143{}
#[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("lookup_stability",
                                    "rustc_passes::stability", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_passes/src/stability.rs"),
                                    ::tracing_core::__macro_support::Option::Some(143u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_passes::stability"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        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(&def_id)
                                                            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: Option<Stability> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !tcx.features().staged_api() {
                if !tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
                    return None;
                }
                let Some(parent) =
                    tcx.opt_local_parent(def_id) else {
                        return Some(FORCE_UNSTABLE)
                    };
                if inherit_deprecation(tcx.def_kind(def_id)) {
                    let parent = tcx.lookup_stability(parent)?;
                    if parent.is_unstable() { return Some(parent); }
                }
                return None;
            }
            let stab =
                {
                    {
                        'done:
                            {
                            for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx)
                                {
                                #[allow(unused_imports)]
                                use ::rustc_attr_ir::AttributeKind::*;
                                let i: &::rustc_attr_ir::Attribute = i;
                                match i {
                                    ::rustc_attr_ir::Attribute::Parsed(Stability {
                                        stability, span: _ }) => {
                                        break 'done Some(*stability);
                                    }
                                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                        {}
                                        #[deny(unreachable_patterns)]
                                        _ => {}
                                }
                            }
                            None
                        }
                    }
                };
            if let Some(stab) = stab { return Some(stab); }
            if inherit_deprecation(tcx.def_kind(def_id)) {
                let Some(parent) =
                    tcx.opt_local_parent(def_id) else {
                        return tcx.sess.opts.unstable_opts.force_unstable_if_unmarked.then_some(FORCE_UNSTABLE);
                    };
                let parent = tcx.lookup_stability(parent)?;
                if parent.is_unstable() ||
                        inherit_stability(tcx.def_kind(def_id)) {
                    return Some(parent);
                }
            }
            None
        }
    }
}#[instrument(level = "debug", skip(tcx))]
144fn lookup_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<Stability> {
145    // Propagate unstability. This can happen even for non-staged-api crates in case
146    // -Zforce-unstable-if-unmarked is set.
147    if !tcx.features().staged_api() {
148        if !tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
149            return None;
150        }
151
152        let Some(parent) = tcx.opt_local_parent(def_id) else { return Some(FORCE_UNSTABLE) };
153
154        if inherit_deprecation(tcx.def_kind(def_id)) {
155            let parent = tcx.lookup_stability(parent)?;
156            if parent.is_unstable() {
157                return Some(parent);
158            }
159        }
160
161        return None;
162    }
163
164    // # Regular stability
165    let stab = find_attr!(tcx, def_id, Stability { stability, span: _ } => *stability);
166
167    if let Some(stab) = stab {
168        return Some(stab);
169    }
170
171    if inherit_deprecation(tcx.def_kind(def_id)) {
172        let Some(parent) = tcx.opt_local_parent(def_id) else {
173            return tcx
174                .sess
175                .opts
176                .unstable_opts
177                .force_unstable_if_unmarked
178                .then_some(FORCE_UNSTABLE);
179        };
180        let parent = tcx.lookup_stability(parent)?;
181        if parent.is_unstable() || inherit_stability(tcx.def_kind(def_id)) {
182            return Some(parent);
183        }
184    }
185
186    None
187}
188
189{}
#[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("lookup_default_body_stability",
                                    "rustc_passes::stability", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_passes/src/stability.rs"),
                                    ::tracing_core::__macro_support::Option::Some(189u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_passes::stability"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        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(&def_id)
                                                            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: Option<DefaultBodyStability> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !tcx.features().staged_api() { return None; }
            {
                {
                    'done:
                        {
                        for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx)
                            {
                            #[allow(unused_imports)]
                            use ::rustc_attr_ir::AttributeKind::*;
                            let i: &::rustc_attr_ir::Attribute = i;
                            match i {
                                ::rustc_attr_ir::Attribute::Parsed(RustcBodyStability {
                                    stability, .. }) => {
                                    break 'done Some(*stability);
                                }
                                ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                    {}
                                    #[deny(unreachable_patterns)]
                                    _ => {}
                            }
                        }
                        None
                    }
                }
            }
        }
    }
}#[instrument(level = "debug", skip(tcx))]
190fn lookup_default_body_stability(
191    tcx: TyCtxt<'_>,
192    def_id: LocalDefId,
193) -> Option<DefaultBodyStability> {
194    if !tcx.features().staged_api() {
195        return None;
196    }
197
198    // FIXME: check that this item can have body stability
199    find_attr!(tcx, def_id, RustcBodyStability { stability, .. } => *stability)
200}
201
202{}
#[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("lookup_const_stability",
                                    "rustc_passes::stability", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_passes/src/stability.rs"),
                                    ::tracing_core::__macro_support::Option::Some(202u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_passes::stability"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        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(&def_id)
                                                            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: Option<ConstStability> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !tcx.features().staged_api() {
                if inherit_deprecation(tcx.def_kind(def_id)) {
                    let parent = tcx.opt_local_parent(def_id)?;
                    let parent_stab = tcx.lookup_stability(parent)?;
                    if parent_stab.is_unstable() &&
                                let Some(fn_sig) = tcx.hir_node_by_def_id(def_id).fn_sig()
                            &&
                            #[allow(non_exhaustive_omitted_patterns)] match fn_sig.header.constness
                                {
                                Constness::Const { .. } => true,
                                _ => false,
                            } {
                        let const_stable_indirect =
                            {
                                    {
                                        'done:
                                            {
                                            for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx)
                                                {
                                                #[allow(unused_imports)]
                                                use ::rustc_attr_ir::AttributeKind::*;
                                                let i: &::rustc_attr_ir::Attribute = i;
                                                match i {
                                                    ::rustc_attr_ir::Attribute::Parsed(RustcConstStableIndirect)
                                                        => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }
                                }.is_some();
                        return Some(ConstStability::unmarked(const_stable_indirect,
                                    parent_stab));
                    }
                }
                return None;
            }
            let const_stable_indirect =
                {
                        {
                            'done:
                                {
                                for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx)
                                    {
                                    #[allow(unused_imports)]
                                    use ::rustc_attr_ir::AttributeKind::*;
                                    let i: &::rustc_attr_ir::Attribute = i;
                                    match i {
                                        ::rustc_attr_ir::Attribute::Parsed(RustcConstStableIndirect)
                                            => {
                                            break 'done Some(());
                                        }
                                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                            {}
                                            #[deny(unreachable_patterns)]
                                            _ => {}
                                    }
                                }
                                None
                            }
                        }
                    }.is_some();
            let const_stab =
                {
                    {
                        'done:
                            {
                            for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx)
                                {
                                #[allow(unused_imports)]
                                use ::rustc_attr_ir::AttributeKind::*;
                                let i: &::rustc_attr_ir::Attribute = i;
                                match i {
                                    ::rustc_attr_ir::Attribute::Parsed(RustcConstStability {
                                        stability, span: _ }) => {
                                        break 'done Some(*stability);
                                    }
                                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                        {}
                                        #[deny(unreachable_patterns)]
                                        _ => {}
                                }
                            }
                            None
                        }
                    }
                };
            let mut const_stab =
                const_stab.map(|const_stab|
                        ConstStability::from_partial(const_stab,
                            const_stable_indirect));
            if let Some(fn_sig) = tcx.hir_node_by_def_id(def_id).fn_sig() &&
                                #[allow(non_exhaustive_omitted_patterns)] match fn_sig.header.constness
                                    {
                                    Constness::Const { .. } => true,
                                    _ => false,
                                } && const_stab.is_none() &&
                        let Some(inherit_regular_stab) =
                            tcx.lookup_stability(def_id) &&
                    inherit_regular_stab.is_unstable() {
                const_stab =
                    Some(ConstStability {
                            const_stable_indirect: true,
                            promotable: false,
                            level: inherit_regular_stab.level,
                            feature: inherit_regular_stab.feature,
                        });
            }
            if let Some(const_stab) = const_stab { return Some(const_stab); }
            if inherit_const_stability(tcx, def_id) {
                let parent = tcx.opt_local_parent(def_id)?;
                let parent = tcx.lookup_const_stability(parent)?;
                if parent.is_const_unstable() { return Some(parent); }
            }
            None
        }
    }
}#[instrument(level = "debug", skip(tcx))]
203fn lookup_const_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ConstStability> {
204    if !tcx.features().staged_api() {
205        // Propagate unstability. This can happen even for non-staged-api crates in case
206        // -Zforce-unstable-if-unmarked is set.
207        if inherit_deprecation(tcx.def_kind(def_id)) {
208            let parent = tcx.opt_local_parent(def_id)?;
209            let parent_stab = tcx.lookup_stability(parent)?;
210            if parent_stab.is_unstable()
211                && let Some(fn_sig) = tcx.hir_node_by_def_id(def_id).fn_sig()
212                && matches!(fn_sig.header.constness, Constness::Const { .. })
213            {
214                let const_stable_indirect = find_attr!(tcx, def_id, RustcConstStableIndirect);
215                return Some(ConstStability::unmarked(const_stable_indirect, parent_stab));
216            }
217        }
218
219        return None;
220    }
221
222    let const_stable_indirect = find_attr!(tcx, def_id, RustcConstStableIndirect);
223    let const_stab =
224        find_attr!(tcx, def_id, RustcConstStability { stability, span: _ } => *stability);
225
226    // After checking the immediate attributes, get rid of the span and compute implied
227    // const stability: inherit feature gate from regular stability.
228    let mut const_stab = const_stab
229        .map(|const_stab| ConstStability::from_partial(const_stab, const_stable_indirect));
230
231    // If this is a const fn but not annotated with stability markers, see if we can inherit
232    // regular stability.
233    if let Some(fn_sig) = tcx.hir_node_by_def_id(def_id).fn_sig()
234        && matches!(fn_sig.header.constness, Constness::Const { .. })
235        && const_stab.is_none()
236        // We only ever inherit unstable features.
237        && let Some(inherit_regular_stab) = tcx.lookup_stability(def_id)
238        && inherit_regular_stab.is_unstable()
239    {
240        const_stab = Some(ConstStability {
241            // We subject these implicitly-const functions to recursive const stability.
242            const_stable_indirect: true,
243            promotable: false,
244            level: inherit_regular_stab.level,
245            feature: inherit_regular_stab.feature,
246        });
247    }
248
249    if let Some(const_stab) = const_stab {
250        return Some(const_stab);
251    }
252
253    // `impl const Trait for Type` items forward their const stability to their immediate children.
254    // FIXME(const_trait_impl): how is this supposed to interact with `#[rustc_const_stable_indirect]`?
255    // Currently, once that is set, we do not inherit anything from the parent any more.
256    if inherit_const_stability(tcx, def_id) {
257        let parent = tcx.opt_local_parent(def_id)?;
258        let parent = tcx.lookup_const_stability(parent)?;
259        if parent.is_const_unstable() {
260            return Some(parent);
261        }
262    }
263
264    None
265}
266
267fn stability_implications(tcx: TyCtxt<'_>, LocalCrate: LocalCrate) -> UnordMap<Symbol, Symbol> {
268    let mut implications = UnordMap::default();
269
270    let mut register_implication = |def_id| {
271        if let Some(stability) = tcx.lookup_stability(def_id)
272            && let StabilityLevel::Unstable { implied_by: Some(implied_by), .. } = stability.level
273        {
274            implications.insert(implied_by, stability.feature);
275        }
276
277        if let Some(stability) = tcx.lookup_const_stability(def_id)
278            && let StabilityLevel::Unstable { implied_by: Some(implied_by), .. } = stability.level
279        {
280            implications.insert(implied_by, stability.feature);
281        }
282    };
283
284    if tcx.features().staged_api() {
285        register_implication(CRATE_DEF_ID);
286        for def_id in tcx.hir_crate_items(()).definitions() {
287            register_implication(def_id);
288            let def_kind = tcx.def_kind(def_id);
289            if def_kind.is_adt() {
290                let adt = tcx.adt_def(def_id);
291                for variant in adt.variants() {
292                    if variant.def_id != def_id.to_def_id() {
293                        register_implication(variant.def_id.expect_local());
294                    }
295                    for field in &variant.fields {
296                        register_implication(field.did.expect_local());
297                    }
298                    if let Some(ctor_def_id) = variant.ctor_def_id() {
299                        register_implication(ctor_def_id.expect_local())
300                    }
301                }
302            }
303            if def_kind.has_generics() {
304                for param in tcx.generics_of(def_id).own_params.iter() {
305                    register_implication(param.def_id.expect_local())
306                }
307            }
308        }
309    }
310
311    implications
312}
313
314struct MissingStabilityAnnotations<'tcx> {
315    tcx: TyCtxt<'tcx>,
316    effective_visibilities: &'tcx EffectiveVisibilities,
317}
318
319impl<'tcx> MissingStabilityAnnotations<'tcx> {
320    /// Verify that deprecation and stability attributes make sense with one another.
321    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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_compatible_stability",
                                    "rustc_passes::stability", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_passes/src/stability.rs"),
                                    ::tracing_core::__macro_support::Option::Some(321u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_passes::stability"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        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::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::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(&def_id)
                                                            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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !self.tcx.features().staged_api() { return; }
            let depr = self.tcx.lookup_deprecation_entry(def_id);
            let stab = self.tcx.lookup_stability(def_id);
            let const_stab = self.tcx.lookup_const_stability(def_id);
            macro_rules! find_attr_span {
                ($name:ident) =>
                {{
                        let attrs =
                        self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id));
                        find_attr!(attrs, AttributeKind::$name { span, .. } =>
                        *span)
                    }}
            }
            if stab.is_none() &&
                        depr.map_or(false, |d| d.attr.is_since_rustc_version()) &&
                    let Some(span) =
                        {
                            let attrs =
                                self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id));
                            {
                                'done:
                                    {
                                    for i in attrs {
                                        #[allow(unused_imports)]
                                        use ::rustc_attr_ir::AttributeKind::*;
                                        let i: &::rustc_attr_ir::Attribute = i;
                                        match i {
                                            ::rustc_attr_ir::Attribute::Parsed(AttributeKind::Deprecated {
                                                span, .. }) => {
                                                break 'done Some(*span);
                                            }
                                            ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                {}
                                                #[deny(unreachable_patterns)]
                                                _ => {}
                                        }
                                    }
                                    None
                                }
                            }
                        } {
                self.tcx.dcx().emit_err(diagnostics::DeprecatedAttribute {
                        span,
                    });
            }
            if let Some(stab) = stab {
                let kind = annotation_kind(self.tcx, def_id);
                if kind == AnnotationKind::Prohibited ||
                        (kind == AnnotationKind::Container && stab.level.is_stable()
                                && depr.is_some()) {
                    if let Some(span) =
                            {
                                let attrs =
                                    self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id));
                                {
                                    'done:
                                        {
                                        for i in attrs {
                                            #[allow(unused_imports)]
                                            use ::rustc_attr_ir::AttributeKind::*;
                                            let i: &::rustc_attr_ir::Attribute = i;
                                            match i {
                                                ::rustc_attr_ir::Attribute::Parsed(AttributeKind::Stability {
                                                    span, .. }) => {
                                                    break 'done Some(*span);
                                                }
                                                ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                    {}
                                                    #[deny(unreachable_patterns)]
                                                    _ => {}
                                            }
                                        }
                                        None
                                    }
                                }
                            } {
                        let item_sp = self.tcx.def_span(def_id);
                        self.tcx.dcx().emit_err(diagnostics::UselessStability {
                                span,
                                item_sp,
                            });
                    }
                }
                if let Some(depr) = depr &&
                                let DeprecatedSince::RustcVersion(dep_since) =
                                    depr.attr.since &&
                            let StabilityLevel::Stable { since: stab_since, .. } =
                                stab.level &&
                        let Some(span) =
                            {
                                let attrs =
                                    self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id));
                                {
                                    'done:
                                        {
                                        for i in attrs {
                                            #[allow(unused_imports)]
                                            use ::rustc_attr_ir::AttributeKind::*;
                                            let i: &::rustc_attr_ir::Attribute = i;
                                            match i {
                                                ::rustc_attr_ir::Attribute::Parsed(AttributeKind::Stability {
                                                    span, .. }) => {
                                                    break 'done Some(*span);
                                                }
                                                ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                    {}
                                                    #[deny(unreachable_patterns)]
                                                    _ => {}
                                            }
                                        }
                                        None
                                    }
                                }
                            } {
                    let item_sp = self.tcx.def_span(def_id);
                    match stab_since {
                        StableSince::Current => {
                            self.tcx.dcx().emit_err(diagnostics::CannotStabilizeDeprecated {
                                    span,
                                    item_sp,
                                });
                        }
                        StableSince::Version(stab_since) => {
                            if dep_since < stab_since {
                                self.tcx.dcx().emit_err(diagnostics::CannotStabilizeDeprecated {
                                        span,
                                        item_sp,
                                    });
                            }
                        }
                        StableSince::Err(_) => {}
                    }
                }
            }
            let fn_sig = self.tcx.hir_node_by_def_id(def_id).fn_sig();
            if let Some(fn_sig) = fn_sig &&
                            !#[allow(non_exhaustive_omitted_patterns)] match fn_sig.header.constness
                                    {
                                    Constness::Const { .. } => true,
                                    _ => false,
                                } && const_stab.is_some() &&
                    {
                            let attrs =
                                self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id));
                            {
                                'done:
                                    {
                                    for i in attrs {
                                        #[allow(unused_imports)]
                                        use ::rustc_attr_ir::AttributeKind::*;
                                        let i: &::rustc_attr_ir::Attribute = i;
                                        match i {
                                            ::rustc_attr_ir::Attribute::Parsed(AttributeKind::RustcConstStability {
                                                span, .. }) => {
                                                break 'done Some(*span);
                                            }
                                            ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                {}
                                                #[deny(unreachable_patterns)]
                                                _ => {}
                                        }
                                    }
                                    None
                                }
                            }
                        }.is_some() {
                self.tcx.dcx().emit_err(diagnostics::MissingConstErr {
                        fn_sig_span: fn_sig.span,
                    });
            }
            if let Some(const_stab) = const_stab && let Some(fn_sig) = fn_sig
                            && const_stab.is_const_stable() &&
                        !stab.is_some_and(|s| s.is_stable()) &&
                    let Some(path_span) =
                        {
                            let attrs =
                                self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id));
                            {
                                'done:
                                    {
                                    for i in attrs {
                                        #[allow(unused_imports)]
                                        use ::rustc_attr_ir::AttributeKind::*;
                                        let i: &::rustc_attr_ir::Attribute = i;
                                        match i {
                                            ::rustc_attr_ir::Attribute::Parsed(AttributeKind::RustcConstStability {
                                                span, .. }) => {
                                                break 'done Some(*span);
                                            }
                                            ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                {}
                                                #[deny(unreachable_patterns)]
                                                _ => {}
                                        }
                                    }
                                    None
                                }
                            }
                        } {
                self.tcx.dcx().emit_err(diagnostics::ConstStableNotStable {
                        fn_sig_span: fn_sig.span,
                        path_span,
                    });
            }
            if let Some(stab) = &const_stab && stab.is_const_stable() &&
                        stab.const_stable_indirect &&
                    let Some(span) =
                        {
                            let attrs =
                                self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id));
                            {
                                'done:
                                    {
                                    for i in attrs {
                                        #[allow(unused_imports)]
                                        use ::rustc_attr_ir::AttributeKind::*;
                                        let i: &::rustc_attr_ir::Attribute = i;
                                        match i {
                                            ::rustc_attr_ir::Attribute::Parsed(AttributeKind::RustcConstStability {
                                                span, .. }) => {
                                                break 'done Some(*span);
                                            }
                                            ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                {}
                                                #[deny(unreachable_patterns)]
                                                _ => {}
                                        }
                                    }
                                    None
                                }
                            }
                        } {
                self.tcx.dcx().emit_err(diagnostics::RustcConstStableIndirectPairing {
                        span,
                    });
            }
        }
    }
}#[instrument(level = "trace", skip(self))]
322    fn check_compatible_stability(&self, def_id: LocalDefId) {
323        if !self.tcx.features().staged_api() {
324            return;
325        }
326
327        let depr = self.tcx.lookup_deprecation_entry(def_id);
328        let stab = self.tcx.lookup_stability(def_id);
329        let const_stab = self.tcx.lookup_const_stability(def_id);
330
331        macro_rules! find_attr_span {
332            ($name:ident) => {{
333                let attrs = self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id));
334                find_attr!(attrs, AttributeKind::$name { span, .. } => *span)
335            }}
336        }
337
338        if stab.is_none()
339            && depr.map_or(false, |d| d.attr.is_since_rustc_version())
340            && let Some(span) = find_attr_span!(Deprecated)
341        {
342            self.tcx.dcx().emit_err(diagnostics::DeprecatedAttribute { span });
343        }
344
345        if let Some(stab) = stab {
346            // Error if prohibited, or can't inherit anything from a container.
347            let kind = annotation_kind(self.tcx, def_id);
348            if kind == AnnotationKind::Prohibited
349                || (kind == AnnotationKind::Container && stab.level.is_stable() && depr.is_some())
350            {
351                if let Some(span) = find_attr_span!(Stability) {
352                    let item_sp = self.tcx.def_span(def_id);
353                    self.tcx.dcx().emit_err(diagnostics::UselessStability { span, item_sp });
354                }
355            }
356
357            // Check if deprecated_since < stable_since. If it is,
358            // this is *almost surely* an accident.
359            if let Some(depr) = depr
360                && let DeprecatedSince::RustcVersion(dep_since) = depr.attr.since
361                && let StabilityLevel::Stable { since: stab_since, .. } = stab.level
362                && let Some(span) = find_attr_span!(Stability)
363            {
364                let item_sp = self.tcx.def_span(def_id);
365                match stab_since {
366                    StableSince::Current => {
367                        self.tcx
368                            .dcx()
369                            .emit_err(diagnostics::CannotStabilizeDeprecated { span, item_sp });
370                    }
371                    StableSince::Version(stab_since) => {
372                        if dep_since < stab_since {
373                            self.tcx
374                                .dcx()
375                                .emit_err(diagnostics::CannotStabilizeDeprecated { span, item_sp });
376                        }
377                    }
378                    StableSince::Err(_) => {
379                        // An error already reported. Assume the unparseable stabilization
380                        // version is older than the deprecation version.
381                    }
382                }
383            }
384        }
385
386        // If the current node is a function with const stability attributes (directly given or
387        // implied), check if the function/method is const or the parent impl block is const.
388        let fn_sig = self.tcx.hir_node_by_def_id(def_id).fn_sig();
389        if let Some(fn_sig) = fn_sig
390            && !matches!(fn_sig.header.constness, Constness::Const { .. })
391            && const_stab.is_some()
392            && find_attr_span!(RustcConstStability).is_some()
393        {
394            self.tcx.dcx().emit_err(diagnostics::MissingConstErr { fn_sig_span: fn_sig.span });
395        }
396
397        // If this is marked const *stable*, it must also be regular-stable.
398        if let Some(const_stab) = const_stab
399            && let Some(fn_sig) = fn_sig
400            && const_stab.is_const_stable()
401            && !stab.is_some_and(|s| s.is_stable())
402            && let Some(path_span) = find_attr_span!(RustcConstStability)
403        {
404            self.tcx.dcx().emit_err(diagnostics::ConstStableNotStable {
405                fn_sig_span: fn_sig.span,
406                path_span,
407            });
408        }
409
410        if let Some(stab) = &const_stab
411            && stab.is_const_stable()
412            && stab.const_stable_indirect
413            && let Some(span) = find_attr_span!(RustcConstStability)
414        {
415            self.tcx.dcx().emit_err(diagnostics::RustcConstStableIndirectPairing { span });
416        }
417    }
418
419    {}
#[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_missing_stability",
                                    "rustc_passes::stability", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_passes/src/stability.rs"),
                                    ::tracing_core::__macro_support::Option::Some(419u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_passes::stability"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        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(&def_id)
                                                            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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let stab = self.tcx.lookup_stability(def_id);
            self.tcx.ensure_ok().lookup_const_stability(def_id);
            if !self.tcx.sess.is_test_crate() && stab.is_none() &&
                    self.effective_visibilities.is_reachable(def_id) {
                let descr = self.tcx.def_descr(def_id.to_def_id());
                let span = self.tcx.def_span(def_id);
                self.tcx.dcx().emit_err(diagnostics::MissingStabilityAttr {
                        span,
                        descr,
                    });
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
420    fn check_missing_stability(&self, def_id: LocalDefId) {
421        let stab = self.tcx.lookup_stability(def_id);
422        self.tcx.ensure_ok().lookup_const_stability(def_id);
423        if !self.tcx.sess.is_test_crate()
424            && stab.is_none()
425            && self.effective_visibilities.is_reachable(def_id)
426        {
427            let descr = self.tcx.def_descr(def_id.to_def_id());
428            let span = self.tcx.def_span(def_id);
429            self.tcx.dcx().emit_err(diagnostics::MissingStabilityAttr { span, descr });
430        }
431    }
432
433    fn check_missing_const_stability(&self, def_id: LocalDefId) {
434        let is_const = self.tcx.is_const_fn(def_id.to_def_id())
435            || (self.tcx.def_kind(def_id.to_def_id()) == DefKind::Trait
436                && self.tcx.is_const_trait(def_id.to_def_id()));
437
438        // Reachable const fn/trait must have a stability attribute.
439        if is_const
440            && self.effective_visibilities.is_reachable(def_id)
441            && self.tcx.lookup_const_stability(def_id).is_none()
442        {
443            let span = self.tcx.def_span(def_id);
444            let descr = self.tcx.def_descr(def_id.to_def_id());
445            self.tcx.dcx().emit_err(diagnostics::MissingConstStabAttr { span, descr });
446        }
447    }
448}
449
450impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> {
451    type NestedFilter = nested_filter::OnlyBodies;
452
453    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
454        self.tcx
455    }
456
457    fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
458        self.check_compatible_stability(i.owner_id.def_id);
459
460        // Inherent impls and foreign modules serve only as containers for other items,
461        // they don't have their own stability. They still can be annotated as unstable
462        // and propagate this instability to children, but this annotation is completely
463        // optional. They inherit stability from their parents when unannotated.
464        if !#[allow(non_exhaustive_omitted_patterns)] match i.kind {
    hir::ItemKind::Impl(hir::Impl { of_trait: None, .. }) |
        hir::ItemKind::ForeignMod { .. } => true,
    _ => false,
}matches!(
465            i.kind,
466            hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
467                | hir::ItemKind::ForeignMod { .. }
468        ) {
469            self.check_missing_stability(i.owner_id.def_id);
470        }
471
472        // Ensure stable `const fn` have a const stability attribute.
473        self.check_missing_const_stability(i.owner_id.def_id);
474
475        intravisit::walk_item(self, i)
476    }
477
478    fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
479        self.check_compatible_stability(ti.owner_id.def_id);
480        self.check_missing_stability(ti.owner_id.def_id);
481        intravisit::walk_trait_item(self, ti);
482    }
483
484    fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
485        self.check_compatible_stability(ii.owner_id.def_id);
486        if let hir::ImplItemImplKind::Inherent { .. } = ii.impl_kind {
487            self.check_missing_stability(ii.owner_id.def_id);
488            self.check_missing_const_stability(ii.owner_id.def_id);
489        }
490        intravisit::walk_impl_item(self, ii);
491    }
492
493    fn visit_variant(&mut self, var: &'tcx Variant<'tcx>) {
494        self.check_compatible_stability(var.def_id);
495        self.check_missing_stability(var.def_id);
496        if let Some(ctor_def_id) = var.data.ctor_def_id() {
497            self.check_missing_stability(ctor_def_id);
498        }
499        intravisit::walk_variant(self, var);
500    }
501
502    fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
503        self.check_compatible_stability(s.def_id);
504        self.check_missing_stability(s.def_id);
505        intravisit::walk_field_def(self, s);
506    }
507
508    fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
509        self.check_compatible_stability(i.owner_id.def_id);
510        self.check_missing_stability(i.owner_id.def_id);
511        intravisit::walk_foreign_item(self, i);
512    }
513
514    fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
515        self.check_compatible_stability(p.def_id);
516        // Note that we don't need to `check_missing_stability` for default generic parameters,
517        // as we assume that any default generic parameters without attributes are automatically
518        // stable (assuming they have not inherited instability from their parent).
519        intravisit::walk_generic_param(self, p);
520    }
521}
522
523/// Cross-references the feature names of unstable APIs with enabled
524/// features and possibly prints errors.
525fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, mod_id: LocalModId) {
526    tcx.hir_visit_item_likes_in_module(mod_id, &mut Checker { tcx });
527
528    let is_staged_api =
529        tcx.sess.opts.unstable_opts.force_unstable_if_unmarked || tcx.features().staged_api();
530    if is_staged_api {
531        let effective_visibilities = &tcx.effective_visibilities(());
532        let mut missing = MissingStabilityAnnotations { tcx, effective_visibilities };
533        if mod_id.is_top_level_module() {
534            missing.check_missing_stability(CRATE_DEF_ID);
535        }
536        tcx.hir_visit_item_likes_in_module(mod_id, &mut missing);
537    }
538
539    if mod_id.is_top_level_module() {
540        check_unused_or_stable_features(tcx)
541    }
542}
543
544pub(crate) fn provide(providers: &mut Providers) {
545    *providers = Providers {
546        check_mod_unstable_api_usage,
547        stability_implications,
548        lookup_stability,
549        lookup_const_stability,
550        lookup_default_body_stability,
551        lookup_deprecation_entry,
552        ..*providers
553    };
554}
555
556struct Checker<'tcx> {
557    tcx: TyCtxt<'tcx>,
558}
559
560impl<'tcx> Visitor<'tcx> for Checker<'tcx> {
561    type NestedFilter = nested_filter::OnlyBodies;
562
563    /// Because stability levels are scoped lexically, we want to walk
564    /// nested items in the context of the outer item, so enable
565    /// deep-walking.
566    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
567        self.tcx
568    }
569
570    fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
571        match item.kind {
572            hir::ItemKind::ExternCrate(_, ident) => {
573                // compiler-generated `extern crate` items have a dummy span.
574                // `std` is still checked for the `restricted-std` feature.
575                if item.span.is_dummy() && ident.name != sym::std {
576                    return;
577                }
578
579                let Some(cnum) = self.tcx.extern_mod_stmt_cnum(item.owner_id.def_id) else {
580                    return;
581                };
582                let def_id = cnum.as_def_id();
583                self.tcx.check_stability(def_id, Some(item.hir_id()), item.span, None);
584            }
585
586            // For implementations of traits, check the stability of each item
587            // individually as it's possible to have a stable trait with unstable
588            // items.
589            hir::ItemKind::Impl(hir::Impl {
590                of_trait: Some(of_trait),
591                self_ty,
592                items,
593                constness,
594                ..
595            }) => {
596                let features = self.tcx.features();
597                if features.staged_api() {
598                    let attrs = self.tcx.hir_attrs(item.hir_id());
599                    let stab = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use ::rustc_attr_ir::AttributeKind::*;
            let i: &::rustc_attr_ir::Attribute = i;
            match i {
                ::rustc_attr_ir::Attribute::Parsed(Stability { stability, span
                    }) => {
                    break 'done Some((*stability, *span));
                }
                ::rustc_attr_ir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, Stability{stability, span} => (*stability, *span));
600
601                    // FIXME(jdonszelmann): make it impossible to miss the or_else in the typesystem
602                    let const_stab =
603                        {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use ::rustc_attr_ir::AttributeKind::*;
            let i: &::rustc_attr_ir::Attribute = i;
            match i {
                ::rustc_attr_ir::Attribute::Parsed(RustcConstStability {
                    stability, .. }) => {
                    break 'done Some(*stability);
                }
                ::rustc_attr_ir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, RustcConstStability{stability, ..} => *stability);
604
605                    let unstable_feature_stab = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use ::rustc_attr_ir::AttributeKind::*;
            let i: &::rustc_attr_ir::Attribute = i;
            match i {
                ::rustc_attr_ir::Attribute::Parsed(UnstableFeatureBound(i)) =>
                    {
                    break 'done Some(i);
                }
                ::rustc_attr_ir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, UnstableFeatureBound(i) => i)
606                        .map(|i| i.as_slice())
607                        .unwrap_or_default();
608
609                    // If this impl block has an #[unstable] attribute, give an
610                    // error if all involved types and traits are stable, because
611                    // it will have no effect.
612                    // See: https://github.com/rust-lang/rust/issues/55436
613                    //
614                    // The exception is when there are both  #[unstable_feature_bound(..)] and
615                    //  #![unstable(feature = "..", issue = "..")] that have the same symbol because
616                    // that can effectively mark an impl as unstable.
617                    //
618                    // For example:
619                    // ```
620                    // #[unstable_feature_bound(feat_foo)]
621                    // #[unstable(feature = "feat_foo", issue = "none")]
622                    // impl Foo for Bar {}
623                    // ```
624                    if let Some((
625                        Stability { level: StabilityLevel::Unstable { .. }, feature },
626                        span,
627                    )) = stab
628                    {
629                        let mut c = CheckTraitImplStable { tcx: self.tcx, fully_stable: true };
630                        c.visit_ty_unambig(self_ty);
631                        c.visit_trait_ref(&of_trait.trait_ref);
632
633                        // Skip the lint if the impl is marked as unstable using
634                        // #[unstable_feature_bound(..)]
635                        let mut unstable_feature_bound_in_effect = false;
636                        for (unstable_bound_feat_name, _) in unstable_feature_stab {
637                            if *unstable_bound_feat_name == feature {
638                                unstable_feature_bound_in_effect = true;
639                            }
640                        }
641
642                        // do not lint when the trait isn't resolved, since resolution error should
643                        // be fixed first
644                        if of_trait.trait_ref.path.res != Res::Err
645                            && c.fully_stable
646                            && !unstable_feature_bound_in_effect
647                        {
648                            self.tcx.emit_node_span_lint(
649                                INEFFECTIVE_UNSTABLE_TRAIT_IMPL,
650                                item.hir_id(),
651                                span,
652                                diagnostics::IneffectiveUnstableImpl,
653                            );
654                        }
655                    }
656
657                    if features.const_trait_impl()
658                        && let hir::Constness::Const { .. } = constness
659                    {
660                        let stable_or_implied_stable = match const_stab {
661                            None => true,
662                            Some(stab) if stab.is_const_stable() => {
663                                // `#![feature(const_trait_impl)]` is unstable, so any impl declared stable
664                                // needs to have an error emitted.
665                                // Note: Remove this error once `const_trait_impl` is stabilized
666                                self.tcx.dcx().emit_err(diagnostics::TraitImplConstStable {
667                                    span: item.span,
668                                });
669                                true
670                            }
671                            Some(_) => false,
672                        };
673
674                        if let Some(trait_id) = of_trait.trait_ref.trait_def_id()
675                            && let Some(const_stab) = self.tcx.lookup_const_stability(trait_id)
676                        {
677                            // the const stability of a trait impl must match the const stability on the trait.
678                            if const_stab.is_const_stable() != stable_or_implied_stable {
679                                let trait_span = self.tcx.def_ident_span(trait_id).unwrap();
680
681                                let impl_stability = if stable_or_implied_stable {
682                                    diagnostics::ImplConstStability::Stable { span: item.span }
683                                } else {
684                                    diagnostics::ImplConstStability::Unstable { span: item.span }
685                                };
686                                let trait_stability = if const_stab.is_const_stable() {
687                                    diagnostics::TraitConstStability::Stable { span: trait_span }
688                                } else {
689                                    diagnostics::TraitConstStability::Unstable { span: trait_span }
690                                };
691
692                                self.tcx.dcx().emit_err(
693                                    diagnostics::TraitImplConstStabilityMismatch {
694                                        span: item.span,
695                                        impl_stability,
696                                        trait_stability,
697                                    },
698                                );
699                            }
700                        }
701                    }
702                }
703
704                if let hir::Constness::Const { .. } = constness
705                    && let Some(def_id) = of_trait.trait_ref.trait_def_id()
706                {
707                    // FIXME(const_trait_impl): Improve the span here.
708                    self.tcx.check_const_stability(
709                        def_id,
710                        of_trait.trait_ref.path.span,
711                        of_trait.trait_ref.path.span,
712                    );
713                }
714
715                for impl_item_ref in items {
716                    let impl_item = self.tcx.associated_item(impl_item_ref.owner_id);
717
718                    if let AssocContainer::TraitImpl(Ok(def_id)) = impl_item.container {
719                        // Pass `None` to skip deprecation warnings.
720                        self.tcx.check_stability(
721                            def_id,
722                            None,
723                            self.tcx.def_span(impl_item_ref.owner_id),
724                            None,
725                        );
726                    }
727                }
728            }
729
730            _ => (/* pass */),
731        }
732        intravisit::walk_item(self, item);
733    }
734
735    fn visit_poly_trait_ref(&mut self, t: &'tcx hir::PolyTraitRef<'tcx>) {
736        match t.modifiers.constness {
737            hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) => {
738                if let Some(def_id) = t.trait_ref.trait_def_id() {
739                    self.tcx.check_const_stability(def_id, t.trait_ref.path.span, span);
740                }
741            }
742            hir::BoundConstness::Never => {}
743        }
744        intravisit::walk_poly_trait_ref(self, t);
745    }
746
747    fn visit_use(&mut self, path: &'tcx UsePath<'tcx>, hir_id: HirId) {
748        let res = path.res;
749
750        // A use item can import something from two namespaces at the same time.
751        // For deprecation/stability we don't want to warn twice.
752        // This specifically happens with constructors for unit/tuple structs.
753        if let Some(ty_ns_res) = res.type_ns
754            && let Some(value_ns_res) = res.value_ns
755            && let Some(type_ns_did) = ty_ns_res.opt_def_id()
756            && let Some(value_ns_did) = value_ns_res.opt_def_id()
757            && let DefKind::Ctor(.., _) = self.tcx.def_kind(value_ns_did)
758            && self.tcx.parent(value_ns_did) == type_ns_did
759        {
760            // Only visit the value namespace path when we've detected a duplicate,
761            // not the type namespace path.
762            let UsePath { segments, res: _, span } = *path;
763            self.visit_path(&Path { segments, res: value_ns_res, span }, hir_id);
764
765            // Though, visit the macro namespace if it exists,
766            // regardless of the checks above relating to constructors.
767            if let Some(res) = res.macro_ns {
768                self.visit_path(&Path { segments, res, span }, hir_id);
769            }
770        } else {
771            // if there's no duplicate, just walk as normal
772            intravisit::walk_use(self, path, hir_id)
773        }
774    }
775
776    fn visit_path(&mut self, path: &hir::Path<'tcx>, id: hir::HirId) {
777        if let Some(def_id) = path.res.opt_def_id() {
778            let method_span = path.segments.last().map(|s| s.ident.span);
779            let item_is_allowed = self.tcx.check_stability_allow_unstable(
780                def_id,
781                Some(id),
782                path.span,
783                method_span,
784                if is_unstable_reexport(self.tcx, id) {
785                    AllowUnstable::Yes
786                } else {
787                    AllowUnstable::No
788                },
789            );
790
791            if item_is_allowed {
792                // The item itself is allowed; check whether the path there is also allowed.
793                let is_allowed_through_unstable_modules: Option<Symbol> =
794                    self.tcx.lookup_stability(def_id).and_then(|stab| match stab.level {
795                        StabilityLevel::Stable { allowed_through_unstable_modules, .. } => {
796                            allowed_through_unstable_modules
797                        }
798                        _ => None,
799                    });
800
801                // Check parent modules stability as well if the item the path refers to is itself
802                // stable. We only emit errors for unstable path segments if the item is stable
803                // or allowed because stability is often inherited, so the most common case is that
804                // both the segments and the item are unstable behind the same feature flag.
805                //
806                // We check here rather than in `visit_path_segment` to prevent visiting the last
807                // path segment twice
808                //
809                // We include special cases via #[rustc_allowed_through_unstable_modules] for items
810                // that were accidentally stabilized through unstable paths before this check was
811                // added, such as `core::intrinsics::transmute`
812                let parents = path.segments.iter().rev().skip(1);
813                for path_segment in parents {
814                    if let Some(def_id) = path_segment.res.opt_def_id() {
815                        match is_allowed_through_unstable_modules {
816                            None => {
817                                // Emit a hard stability error if this path is not stable.
818
819                                // use `None` for id to prevent deprecation check
820                                self.tcx.check_stability_allow_unstable(
821                                    def_id,
822                                    None,
823                                    path_segment.ident.span,
824                                    None,
825                                    if is_unstable_reexport(self.tcx, id) {
826                                        AllowUnstable::Yes
827                                    } else {
828                                        AllowUnstable::No
829                                    },
830                                );
831                            }
832                            Some(deprecation) => {
833                                // Call the stability check directly so that we can control which
834                                // diagnostic is emitted.
835                                let eval_result = self.tcx.eval_stability_allow_unstable(
836                                    def_id,
837                                    None,
838                                    path.span,
839                                    None,
840                                    if is_unstable_reexport(self.tcx, id) {
841                                        AllowUnstable::Yes
842                                    } else {
843                                        AllowUnstable::No
844                                    },
845                                );
846                                let is_allowed = #[allow(non_exhaustive_omitted_patterns)] match eval_result {
    EvalResult::Allow => true,
    _ => false,
}matches!(eval_result, EvalResult::Allow);
847                                if !is_allowed {
848                                    // Calculating message for lint involves calling `self.def_path_str`,
849                                    // which will by default invoke the expensive `visible_parent_map` query.
850                                    // Skip all that work if the lint is allowed anyway.
851                                    if self.tcx.lint_level_spec_at_node(DEPRECATED, id).is_allow() {
852                                        return;
853                                    }
854                                    // Show a deprecation message.
855                                    let def_path =
856                                        { let _guard = NoTrimmedGuard::new(); self.tcx.def_path_str(def_id) }with_no_trimmed_paths!(self.tcx.def_path_str(def_id));
857                                    let def_kind = self.tcx.def_descr(def_id);
858                                    let diag = Deprecated {
859                                        sub: None,
860                                        kind: def_kind.to_owned(),
861                                        path: def_path,
862                                        note: Some(deprecation),
863                                        since_kind: lint::DeprecatedSinceKind::InEffect,
864                                    };
865                                    self.tcx.emit_node_span_lint(
866                                        DEPRECATED,
867                                        id,
868                                        method_span.unwrap_or(path.span),
869                                        diag,
870                                    );
871                                }
872                            }
873                        }
874                    }
875                }
876            }
877        }
878
879        intravisit::walk_path(self, path)
880    }
881}
882
883/// Check whether a path is a `use` item that has been marked as unstable.
884///
885/// See issue #94972 for details on why this is a special case
886fn is_unstable_reexport(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
887    // Get the LocalDefId so we can lookup the item to check the kind.
888    let Some(owner) = id.as_owner() else {
889        return false;
890    };
891    let def_id = owner.def_id;
892
893    let Some(stab) = tcx.lookup_stability(def_id) else {
894        return false;
895    };
896
897    if stab.level.is_stable() {
898        // The re-export is not marked as unstable, don't override
899        return false;
900    }
901
902    // If this is a path that isn't a use, we don't need to do anything special
903    if !#[allow(non_exhaustive_omitted_patterns)] match tcx.hir_expect_item(def_id).kind
    {
    ItemKind::Use(..) => true,
    _ => false,
}matches!(tcx.hir_expect_item(def_id).kind, ItemKind::Use(..)) {
904        return false;
905    }
906
907    true
908}
909
910struct CheckTraitImplStable<'tcx> {
911    tcx: TyCtxt<'tcx>,
912    fully_stable: bool,
913}
914
915impl<'tcx> Visitor<'tcx> for CheckTraitImplStable<'tcx> {
916    fn visit_path(&mut self, path: &hir::Path<'tcx>, _id: hir::HirId) {
917        if let Some(def_id) = path.res.opt_def_id()
918            && let Some(stab) = self.tcx.lookup_stability(def_id)
919        {
920            self.fully_stable &= stab.level.is_stable();
921        }
922        intravisit::walk_path(self, path)
923    }
924
925    fn visit_trait_ref(&mut self, t: &'tcx TraitRef<'tcx>) {
926        if let Res::Def(DefKind::Trait, trait_did) = t.path.res {
927            if let Some(stab) = self.tcx.lookup_stability(trait_did) {
928                self.fully_stable &= stab.level.is_stable();
929            }
930        }
931        intravisit::walk_trait_ref(self, t)
932    }
933
934    fn visit_ty(&mut self, t: &'tcx Ty<'tcx, AmbigArg>) {
935        if let TyKind::Never = t.kind {
936            self.fully_stable = false;
937        }
938        if let TyKind::FnPtr(function) = t.kind {
939            if extern_abi_stability(function.abi).is_err() {
940                self.fully_stable = false;
941            }
942        }
943        intravisit::walk_ty(self, t)
944    }
945
946    fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {
947        for ty in fd.inputs {
948            self.visit_ty_unambig(ty)
949        }
950        if let hir::FnRetTy::Return(output_ty) = fd.output {
951            match output_ty.kind {
952                TyKind::Never => {} // `-> !` is stable
953                _ => self.visit_ty_unambig(output_ty),
954            }
955        }
956    }
957}
958
959/// Given the list of enabled features that were not language features (i.e., that
960/// were expected to be library features), and the list of features used from
961/// libraries, identify activated features that don't exist and error about them.
962// This is `pub` for rustdoc. rustc should call it through `check_mod_unstable_api_usage`.
963pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {
964    let _prof_timer = tcx.sess.timer("unused_lib_feature_checking");
965
966    let enabled_lang_features = tcx.features().enabled_lang_features();
967    let mut lang_features = UnordSet::default();
968    for EnabledLangFeature { gate_name, attr_sp, stable_since } in enabled_lang_features {
969        if let Some(version) = stable_since {
970            // Mark the feature as enabled, to ensure that it is not marked as unused.
971            let _ = tcx.features().enabled(*gate_name);
972
973            // Warn if the user has enabled an already-stable lang feature.
974            unnecessary_stable_feature_lint(tcx, *attr_sp, *gate_name, *version);
975        }
976        if !lang_features.insert(gate_name) {
977            // Warn if the user enables a lang feature multiple times.
978            duplicate_feature_lint(tcx, *attr_sp, *gate_name);
979        }
980    }
981
982    let enabled_lib_features = tcx.features().enabled_lib_features();
983    let mut remaining_lib_features = FxIndexMap::default();
984    for EnabledLibFeature { gate_name, attr_sp } in enabled_lib_features {
985        if remaining_lib_features.contains_key(gate_name) {
986            // Warn if the user enables a lib feature multiple times.
987            duplicate_feature_lint(tcx, *attr_sp, *gate_name);
988        }
989        remaining_lib_features.insert(*gate_name, *attr_sp);
990    }
991    // `stdbuild` has special handling for `libc`, so we need to
992    // recognise the feature when building std.
993    // Likewise, libtest is handled specially, so `test` isn't
994    // available as we'd like it to be.
995    // FIXME: only remove `libc` when `stdbuild` is enabled.
996    // FIXME: remove special casing for `test`.
997    // FIXME(#120456) - is `swap_remove` correct?
998    remaining_lib_features.swap_remove(&sym::libc);
999    remaining_lib_features.swap_remove(&sym::test);
1000
1001    /// For each feature in `defined_features`..
1002    ///
1003    /// - If it is in `remaining_lib_features` (those features with `#![feature(..)]` attributes in
1004    ///   the current crate), check if it is stable (or partially stable) and thus an unnecessary
1005    ///   attribute.
1006    /// - If it is in `remaining_implications` (a feature that is referenced by an `implied_by`
1007    ///   from the current crate), then remove it from the remaining implications.
1008    ///
1009    /// Once this function has been invoked for every feature (local crate and all extern crates),
1010    /// then..
1011    ///
1012    /// - If features remain in `remaining_lib_features`, then the user has enabled a feature that
1013    ///   does not exist.
1014    /// - If features remain in `remaining_implications`, the `implied_by` refers to a feature that
1015    ///   does not exist.
1016    ///
1017    /// By structuring the code in this way: checking the features defined from each crate one at a
1018    /// time, less loading from metadata is performed and thus compiler performance is improved.
1019    fn check_features<'tcx>(
1020        tcx: TyCtxt<'tcx>,
1021        remaining_lib_features: &mut FxIndexMap<Symbol, Span>,
1022        remaining_implications: &mut UnordMap<Symbol, Symbol>,
1023        defined_features: &LibFeatures,
1024        all_implications: &UnordMap<Symbol, Symbol>,
1025    ) {
1026        for (feature, stability) in defined_features.to_sorted_vec() {
1027            if let FeatureStability::AcceptedSince(since) = stability
1028                && let Some(span) = remaining_lib_features.get(&feature)
1029            {
1030                // Mark the feature as enabled, to ensure that it is not marked as unused.
1031                let _ = tcx.features().enabled(feature);
1032
1033                // Warn if the user has enabled an already-stable lib feature.
1034                if let Some(implies) = all_implications.get(&feature) {
1035                    unnecessary_partially_stable_feature_lint(tcx, *span, feature, *implies, since);
1036                } else {
1037                    unnecessary_stable_feature_lint(tcx, *span, feature, since);
1038                }
1039            }
1040            // FIXME(#120456) - is `swap_remove` correct?
1041            remaining_lib_features.swap_remove(&feature);
1042
1043            // `feature` is the feature doing the implying, but `implied_by` is the feature with
1044            // the attribute that establishes this relationship. `implied_by` is guaranteed to be a
1045            // feature defined in the local crate because `remaining_implications` is only the
1046            // implications from this crate.
1047            remaining_implications.remove(&feature);
1048
1049            if let FeatureStability::Unstable { old_name: Some(alias) } = stability
1050                && let Some(span) = remaining_lib_features.swap_remove(&alias)
1051            {
1052                tcx.dcx().emit_err(diagnostics::RenamedFeature { span, feature, alias });
1053            }
1054
1055            if remaining_lib_features.is_empty() && remaining_implications.is_empty() {
1056                break;
1057            }
1058        }
1059    }
1060
1061    // All local crate implications need to have the feature that implies it confirmed to exist.
1062    let mut remaining_implications = tcx.stability_implications(LOCAL_CRATE).clone();
1063
1064    // We always collect the lib features enabled in the current crate, even if there are
1065    // no unknown features, because the collection also does feature attribute validation.
1066    let local_defined_features = tcx.lib_features(LOCAL_CRATE);
1067    if !remaining_lib_features.is_empty() || !remaining_implications.is_empty() {
1068        let crates = tcx.crates(());
1069
1070        // Loading the implications of all crates is unavoidable to be able to emit the partial
1071        // stabilization diagnostic, but it can be avoided when there are no
1072        // `remaining_lib_features`.
1073        let mut all_implications = remaining_implications.clone();
1074        for &cnum in crates {
1075            all_implications
1076                .extend_unord(tcx.stability_implications(cnum).items().map(|(k, v)| (*k, *v)));
1077        }
1078
1079        check_features(
1080            tcx,
1081            &mut remaining_lib_features,
1082            &mut remaining_implications,
1083            local_defined_features,
1084            &all_implications,
1085        );
1086
1087        for &cnum in crates {
1088            if remaining_lib_features.is_empty() && remaining_implications.is_empty() {
1089                break;
1090            }
1091            check_features(
1092                tcx,
1093                &mut remaining_lib_features,
1094                &mut remaining_implications,
1095                tcx.lib_features(cnum),
1096                &all_implications,
1097            );
1098        }
1099
1100        if !remaining_lib_features.is_empty() {
1101            let lang_features =
1102                UNSTABLE_LANG_FEATURES.iter().map(|feature| feature.name).collect::<Vec<_>>();
1103            let lib_features = crates
1104                .iter()
1105                .flat_map(|&cnum| {
1106                    tcx.lib_features(cnum).stability.keys().copied().into_sorted_stable_ord()
1107                })
1108                .collect::<Vec<_>>();
1109
1110            let valid_feature_names = [lang_features, lib_features].concat();
1111
1112            // Collect all of the marked as "removed" features
1113            let unstable_removed_features = crates
1114                .iter()
1115                .flat_map(|&cnum| {
1116                    {
    {
        'done:
            {
            for i in
                ::rustc_attr_ir::HasAttrs::get_attrs(cnum.as_def_id(), &tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(UnstableRemoved(rem_features))
                        => {
                        break 'done Some(rem_features);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, cnum.as_def_id(), UnstableRemoved(rem_features) => rem_features)
1117                        .into_flat_iter()
1118                })
1119                .collect::<Vec<_>>();
1120
1121            for (feature, span) in remaining_lib_features {
1122                if let Some(removed) =
1123                    unstable_removed_features.iter().find(|removed| removed.feature == feature)
1124                {
1125                    tcx.dcx().emit_err(diagnostics::FeatureRemoved {
1126                        span,
1127                        feature,
1128                        reason: removed.reason,
1129                        link: removed.link,
1130                        since: removed.since.to_string(),
1131                    });
1132                } else {
1133                    let suggestion =
1134                        feature.find_similar(&valid_feature_names).map(|(actual_name, _)| {
1135                            diagnostics::MisspelledFeature { span, actual_name }
1136                        });
1137                    tcx.dcx().emit_err(diagnostics::UnknownFeature { span, feature, suggestion });
1138                }
1139            }
1140        }
1141    }
1142
1143    for (&implied_by, &feature) in remaining_implications.to_sorted_stable_ord() {
1144        let local_defined_features = tcx.lib_features(LOCAL_CRATE);
1145        let span = local_defined_features
1146            .stability
1147            .get(&feature)
1148            .expect("feature that implied another does not exist")
1149            .1;
1150        tcx.dcx().emit_err(diagnostics::ImpliedFeatureNotExist { span, feature, implied_by });
1151    }
1152}
1153
1154fn unnecessary_partially_stable_feature_lint(
1155    tcx: TyCtxt<'_>,
1156    span: Span,
1157    feature: Symbol,
1158    implies: Symbol,
1159    since: Symbol,
1160) {
1161    tcx.emit_node_span_lint(
1162        STABLE_FEATURES,
1163        hir::CRATE_HIR_ID,
1164        span,
1165        diagnostics::UnnecessaryPartialStableFeature {
1166            span,
1167            line: tcx.sess.source_map().span_extend_to_line(span),
1168            feature,
1169            since,
1170            implies,
1171        },
1172    );
1173}
1174
1175fn unnecessary_stable_feature_lint(
1176    tcx: TyCtxt<'_>,
1177    span: Span,
1178    feature: Symbol,
1179    mut since: Symbol,
1180) {
1181    if since.as_str() == VERSION_PLACEHOLDER {
1182        since = sym::env_CFG_RELEASE;
1183    }
1184    tcx.emit_node_span_lint(
1185        STABLE_FEATURES,
1186        hir::CRATE_HIR_ID,
1187        span,
1188        diagnostics::UnnecessaryStableFeature { feature, since },
1189    );
1190}
1191
1192fn duplicate_feature_lint(tcx: TyCtxt<'_>, span: Span, feature: Symbol) {
1193    tcx.emit_node_span_lint(
1194        DUPLICATE_FEATURES,
1195        hir::CRATE_HIR_ID,
1196        span,
1197        diagnostics::DuplicateFeature { feature },
1198    );
1199}