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, LocalModDefId};
13use rustc_hir::intravisit::{self, Visitor, VisitorExt};
14use rustc_hir::{
15    self as hir, AmbigArg, ConstStability, DefaultBodyStability, FieldDef, HirId, Item, ItemKind,
16    Path, Stability, StabilityLevel, StableSince, TraitRef, Ty, TyKind, UnstableReason, UsePath,
17    VERSION_PLACEHOLDER, Variant, find_attr,
18};
19use rustc_middle::hir::nested_filter;
20use rustc_middle::middle::lib_features::{FeatureStability, LibFeatures};
21use rustc_middle::middle::privacy::EffectiveVisibilities;
22use rustc_middle::middle::stability::{AllowUnstable, Deprecated, DeprecationEntry, EvalResult};
23use rustc_middle::query::{LocalCrate, Providers};
24use rustc_middle::ty::print::with_no_trimmed_paths;
25use rustc_middle::ty::{AssocContainer, TyCtxt};
26use rustc_session::lint;
27use rustc_session::lint::builtin::{DEPRECATED, INEFFECTIVE_UNSTABLE_TRAIT_IMPL};
28use rustc_span::{Span, Symbol, sym};
29use tracing::instrument;
30
31use crate::errors;
32
33#[derive(#[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)]
34enum AnnotationKind {
35    /// Annotation is required if not inherited from unstable parents.
36    Required,
37    /// Annotation is useless, reject it.
38    Prohibited,
39    /// Deprecation annotation is useless, reject it. (Stability attribute is still required.)
40    DeprecationProhibited,
41    /// Annotation itself is useless, but it can be propagated to children.
42    Container,
43}
44
45fn inherit_deprecation(def_kind: DefKind) -> bool {
46    match def_kind {
47        DefKind::LifetimeParam | DefKind::TyParam | DefKind::ConstParam => false,
48        _ => true,
49    }
50}
51
52fn inherit_const_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
53    let def_kind = tcx.def_kind(def_id);
54    match def_kind {
55        DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst { .. } => {
56            match tcx.def_kind(tcx.local_parent(def_id)) {
57                DefKind::Impl { .. } => true,
58                _ => false,
59            }
60        }
61        _ => false,
62    }
63}
64
65fn annotation_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> AnnotationKind {
66    let def_kind = tcx.def_kind(def_id);
67    match def_kind {
68        // Inherent impls and foreign modules serve only as containers for other items,
69        // they don't have their own stability. They still can be annotated as unstable
70        // and propagate this unstability to children, but this annotation is completely
71        // optional. They inherit stability from their parents when unannotated.
72        DefKind::Impl { of_trait: false } | DefKind::ForeignMod => AnnotationKind::Container,
73        DefKind::Impl { of_trait: true } => AnnotationKind::DeprecationProhibited,
74
75        // Allow stability attributes on default generic arguments.
76        DefKind::TyParam | DefKind::ConstParam => {
77            match &tcx.hir_node_by_def_id(def_id).expect_generic_param().kind {
78                hir::GenericParamKind::Type { default: Some(_), .. }
79                | hir::GenericParamKind::Const { default: Some(_), .. } => {
80                    AnnotationKind::Container
81                }
82                _ => AnnotationKind::Prohibited,
83            }
84        }
85
86        // Impl items in trait impls cannot have stability.
87        DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst { .. } => {
88            match tcx.def_kind(tcx.local_parent(def_id)) {
89                DefKind::Impl { of_trait: true } => AnnotationKind::Prohibited,
90                _ => AnnotationKind::Required,
91            }
92        }
93
94        _ => AnnotationKind::Required,
95    }
96}
97
98fn lookup_deprecation_entry(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<DeprecationEntry> {
99    let depr = {

    #[allow(deprecated)]
    {
        {
            'done:
                {
                for i in tcx.get_all_attrs(def_id) {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(Deprecated {
                            deprecation, span: _ }) => {
                            break 'done Some(*deprecation);
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }
}find_attr!(tcx, def_id,
100        Deprecated { deprecation, span: _ } => *deprecation
101    );
102
103    let Some(depr) = depr else {
104        if inherit_deprecation(tcx.def_kind(def_id)) {
105            let parent_id = tcx.opt_local_parent(def_id)?;
106            let parent_depr = tcx.lookup_deprecation_entry(parent_id)?;
107            return Some(parent_depr);
108        }
109
110        return None;
111    };
112
113    // `Deprecation` is just two pointers, no need to intern it
114    Some(DeprecationEntry::local(depr, def_id))
115}
116
117fn inherit_stability(def_kind: DefKind) -> bool {
118    match def_kind {
119        DefKind::Field | DefKind::Variant | DefKind::Ctor(..) => true,
120        _ => false,
121    }
122}
123
124/// If the `-Z force-unstable-if-unmarked` flag is passed then we provide
125/// a parent stability annotation which indicates that this is private
126/// with the `rustc_private` feature. This is intended for use when
127/// compiling library and `rustc_*` crates themselves so we can leverage crates.io
128/// while maintaining the invariant that all sysroot crates are unstable
129/// by default and are unable to be used.
130const FORCE_UNSTABLE: Stability = Stability {
131    level: StabilityLevel::Unstable {
132        reason: UnstableReason::Default,
133        issue: NonZero::new(27812),
134        is_soft: false,
135        implied_by: None,
136        old_name: None,
137    },
138    feature: sym::rustc_private,
139};
140
141#[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(141u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_passes::stability"),
                                    ::tracing_core::field::FieldSet::new(&["def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: 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 =
                {

                    #[allow(deprecated)]
                    {
                        {
                            'done:
                                {
                                for i in tcx.get_all_attrs(def_id) {
                                    #[allow(unused_imports)]
                                    use rustc_hir::attrs::AttributeKind::*;
                                    let i: &rustc_hir::Attribute = i;
                                    match i {
                                        rustc_hir::Attribute::Parsed(Stability { stability, span: _
                                            }) => {
                                            break 'done Some(*stability);
                                        }
                                        rustc_hir::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))]
142fn lookup_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<Stability> {
143    // Propagate unstability. This can happen even for non-staged-api crates in case
144    // -Zforce-unstable-if-unmarked is set.
145    if !tcx.features().staged_api() {
146        if !tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
147            return None;
148        }
149
150        let Some(parent) = tcx.opt_local_parent(def_id) else { return Some(FORCE_UNSTABLE) };
151
152        if inherit_deprecation(tcx.def_kind(def_id)) {
153            let parent = tcx.lookup_stability(parent)?;
154            if parent.is_unstable() {
155                return Some(parent);
156            }
157        }
158
159        return None;
160    }
161
162    // # Regular stability
163    let stab = find_attr!(tcx, def_id, Stability { stability, span: _ } => *stability);
164
165    if let Some(stab) = stab {
166        return Some(stab);
167    }
168
169    if inherit_deprecation(tcx.def_kind(def_id)) {
170        let Some(parent) = tcx.opt_local_parent(def_id) else {
171            return tcx
172                .sess
173                .opts
174                .unstable_opts
175                .force_unstable_if_unmarked
176                .then_some(FORCE_UNSTABLE);
177        };
178        let parent = tcx.lookup_stability(parent)?;
179        if parent.is_unstable() || inherit_stability(tcx.def_kind(def_id)) {
180            return Some(parent);
181        }
182    }
183
184    None
185}
186
187#[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(187u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_passes::stability"),
                                    ::tracing_core::field::FieldSet::new(&["def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Option<DefaultBodyStability> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !tcx.features().staged_api() { return None; }
            {

                #[allow(deprecated)]
                {
                    {
                        'done:
                            {
                            for i in tcx.get_all_attrs(def_id) {
                                #[allow(unused_imports)]
                                use rustc_hir::attrs::AttributeKind::*;
                                let i: &rustc_hir::Attribute = i;
                                match i {
                                    rustc_hir::Attribute::Parsed(RustcBodyStability { stability,
                                        .. }) => {
                                        break 'done Some(*stability);
                                    }
                                    rustc_hir::Attribute::Unparsed(..) =>
                                        {}
                                        #[deny(unreachable_patterns)]
                                        _ => {}
                                }
                            }
                            None
                        }
                    }
                }
            }
        }
    }
}#[instrument(level = "debug", skip(tcx))]
188fn lookup_default_body_stability(
189    tcx: TyCtxt<'_>,
190    def_id: LocalDefId,
191) -> Option<DefaultBodyStability> {
192    if !tcx.features().staged_api() {
193        return None;
194    }
195
196    // FIXME: check that this item can have body stability
197    find_attr!(tcx, def_id, RustcBodyStability { stability, .. } => *stability)
198}
199
200#[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(200u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_passes::stability"),
                                    ::tracing_core::field::FieldSet::new(&["def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: 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()
                            && fn_sig.header.is_const() {
                        let const_stable_indirect =
                            {

                                    #[allow(deprecated)]
                                    {
                                        {
                                            'done:
                                                {
                                                for i in tcx.get_all_attrs(def_id) {
                                                    #[allow(unused_imports)]
                                                    use rustc_hir::attrs::AttributeKind::*;
                                                    let i: &rustc_hir::Attribute = i;
                                                    match i {
                                                        rustc_hir::Attribute::Parsed(RustcConstStableIndirect) => {
                                                            break 'done Some(());
                                                        }
                                                        rustc_hir::Attribute::Unparsed(..) =>
                                                            {}
                                                            #[deny(unreachable_patterns)]
                                                            _ => {}
                                                    }
                                                }
                                                None
                                            }
                                        }
                                    }
                                }.is_some();
                        return Some(ConstStability::unmarked(const_stable_indirect,
                                    parent_stab));
                    }
                }
                return None;
            }
            let const_stable_indirect =
                {

                        #[allow(deprecated)]
                        {
                            {
                                'done:
                                    {
                                    for i in tcx.get_all_attrs(def_id) {
                                        #[allow(unused_imports)]
                                        use rustc_hir::attrs::AttributeKind::*;
                                        let i: &rustc_hir::Attribute = i;
                                        match i {
                                            rustc_hir::Attribute::Parsed(RustcConstStableIndirect) => {
                                                break 'done Some(());
                                            }
                                            rustc_hir::Attribute::Unparsed(..) =>
                                                {}
                                                #[deny(unreachable_patterns)]
                                                _ => {}
                                        }
                                    }
                                    None
                                }
                            }
                        }
                    }.is_some();
            let const_stab =
                {

                    #[allow(deprecated)]
                    {
                        {
                            'done:
                                {
                                for i in tcx.get_all_attrs(def_id) {
                                    #[allow(unused_imports)]
                                    use rustc_hir::attrs::AttributeKind::*;
                                    let i: &rustc_hir::Attribute = i;
                                    match i {
                                        rustc_hir::Attribute::Parsed(RustcConstStability {
                                            stability, span: _ }) => {
                                            break 'done Some(*stability);
                                        }
                                        rustc_hir::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() &&
                                fn_sig.header.is_const() && 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))]
201fn lookup_const_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ConstStability> {
202    if !tcx.features().staged_api() {
203        // Propagate unstability. This can happen even for non-staged-api crates in case
204        // -Zforce-unstable-if-unmarked is set.
205        if inherit_deprecation(tcx.def_kind(def_id)) {
206            let parent = tcx.opt_local_parent(def_id)?;
207            let parent_stab = tcx.lookup_stability(parent)?;
208            if parent_stab.is_unstable()
209                && let Some(fn_sig) = tcx.hir_node_by_def_id(def_id).fn_sig()
210                && fn_sig.header.is_const()
211            {
212                let const_stable_indirect = find_attr!(tcx, def_id, RustcConstStableIndirect);
213                return Some(ConstStability::unmarked(const_stable_indirect, parent_stab));
214            }
215        }
216
217        return None;
218    }
219
220    let const_stable_indirect = find_attr!(tcx, def_id, RustcConstStableIndirect);
221    let const_stab =
222        find_attr!(tcx, def_id, RustcConstStability { stability, span: _ } => *stability);
223
224    // After checking the immediate attributes, get rid of the span and compute implied
225    // const stability: inherit feature gate from regular stability.
226    let mut const_stab = const_stab
227        .map(|const_stab| ConstStability::from_partial(const_stab, const_stable_indirect));
228
229    // If this is a const fn but not annotated with stability markers, see if we can inherit
230    // regular stability.
231    if let Some(fn_sig) = tcx.hir_node_by_def_id(def_id).fn_sig()
232        && fn_sig.header.is_const()
233        && const_stab.is_none()
234        // We only ever inherit unstable features.
235        && let Some(inherit_regular_stab) = tcx.lookup_stability(def_id)
236        && inherit_regular_stab.is_unstable()
237    {
238        const_stab = Some(ConstStability {
239            // We subject these implicitly-const functions to recursive const stability.
240            const_stable_indirect: true,
241            promotable: false,
242            level: inherit_regular_stab.level,
243            feature: inherit_regular_stab.feature,
244        });
245    }
246
247    if let Some(const_stab) = const_stab {
248        return Some(const_stab);
249    }
250
251    // `impl const Trait for Type` items forward their const stability to their immediate children.
252    // FIXME(const_trait_impl): how is this supposed to interact with `#[rustc_const_stable_indirect]`?
253    // Currently, once that is set, we do not inherit anything from the parent any more.
254    if inherit_const_stability(tcx, def_id) {
255        let parent = tcx.opt_local_parent(def_id)?;
256        let parent = tcx.lookup_const_stability(parent)?;
257        if parent.is_const_unstable() {
258            return Some(parent);
259        }
260    }
261
262    None
263}
264
265fn stability_implications(tcx: TyCtxt<'_>, LocalCrate: LocalCrate) -> UnordMap<Symbol, Symbol> {
266    let mut implications = UnordMap::default();
267
268    let mut register_implication = |def_id| {
269        if let Some(stability) = tcx.lookup_stability(def_id)
270            && let StabilityLevel::Unstable { implied_by: Some(implied_by), .. } = stability.level
271        {
272            implications.insert(implied_by, stability.feature);
273        }
274
275        if let Some(stability) = tcx.lookup_const_stability(def_id)
276            && let StabilityLevel::Unstable { implied_by: Some(implied_by), .. } = stability.level
277        {
278            implications.insert(implied_by, stability.feature);
279        }
280    };
281
282    if tcx.features().staged_api() {
283        register_implication(CRATE_DEF_ID);
284        for def_id in tcx.hir_crate_items(()).definitions() {
285            register_implication(def_id);
286            let def_kind = tcx.def_kind(def_id);
287            if def_kind.is_adt() {
288                let adt = tcx.adt_def(def_id);
289                for variant in adt.variants() {
290                    if variant.def_id != def_id.to_def_id() {
291                        register_implication(variant.def_id.expect_local());
292                    }
293                    for field in &variant.fields {
294                        register_implication(field.did.expect_local());
295                    }
296                    if let Some(ctor_def_id) = variant.ctor_def_id() {
297                        register_implication(ctor_def_id.expect_local())
298                    }
299                }
300            }
301            if def_kind.has_generics() {
302                for param in tcx.generics_of(def_id).own_params.iter() {
303                    register_implication(param.def_id.expect_local())
304                }
305            }
306        }
307    }
308
309    implications
310}
311
312struct MissingStabilityAnnotations<'tcx> {
313    tcx: TyCtxt<'tcx>,
314    effective_visibilities: &'tcx EffectiveVisibilities,
315}
316
317impl<'tcx> MissingStabilityAnnotations<'tcx> {
318    /// Verify that deprecation and stability attributes make sense with one another.
319    #[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(319u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_passes::stability"),
                                    ::tracing_core::field::FieldSet::new(&["def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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_hir::attrs::AttributeKind::*;
                                        let i: &rustc_hir::Attribute = i;
                                        match i {
                                            rustc_hir::Attribute::Parsed(AttributeKind::Deprecated {
                                                span, .. }) => {
                                                break 'done Some(*span);
                                            }
                                            rustc_hir::Attribute::Unparsed(..) =>
                                                {}
                                                #[deny(unreachable_patterns)]
                                                _ => {}
                                        }
                                    }
                                    None
                                }
                            }
                        } {
                self.tcx.dcx().emit_err(errors::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_hir::attrs::AttributeKind::*;
                                            let i: &rustc_hir::Attribute = i;
                                            match i {
                                                rustc_hir::Attribute::Parsed(AttributeKind::Stability {
                                                    span, .. }) => {
                                                    break 'done Some(*span);
                                                }
                                                rustc_hir::Attribute::Unparsed(..) =>
                                                    {}
                                                    #[deny(unreachable_patterns)]
                                                    _ => {}
                                            }
                                        }
                                        None
                                    }
                                }
                            } {
                        let item_sp = self.tcx.def_span(def_id);
                        self.tcx.dcx().emit_err(errors::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_hir::attrs::AttributeKind::*;
                                            let i: &rustc_hir::Attribute = i;
                                            match i {
                                                rustc_hir::Attribute::Parsed(AttributeKind::Stability {
                                                    span, .. }) => {
                                                    break 'done Some(*span);
                                                }
                                                rustc_hir::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(errors::CannotStabilizeDeprecated {
                                    span,
                                    item_sp,
                                });
                        }
                        StableSince::Version(stab_since) => {
                            if dep_since < stab_since {
                                self.tcx.dcx().emit_err(errors::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 && !fn_sig.header.is_const() &&
                        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_hir::attrs::AttributeKind::*;
                                        let i: &rustc_hir::Attribute = i;
                                        match i {
                                            rustc_hir::Attribute::Parsed(AttributeKind::RustcConstStability {
                                                span, .. }) => {
                                                break 'done Some(*span);
                                            }
                                            rustc_hir::Attribute::Unparsed(..) =>
                                                {}
                                                #[deny(unreachable_patterns)]
                                                _ => {}
                                        }
                                    }
                                    None
                                }
                            }
                        }.is_some() {
                self.tcx.dcx().emit_err(errors::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(const_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_hir::attrs::AttributeKind::*;
                                        let i: &rustc_hir::Attribute = i;
                                        match i {
                                            rustc_hir::Attribute::Parsed(AttributeKind::RustcConstStability {
                                                span, .. }) => {
                                                break 'done Some(*span);
                                            }
                                            rustc_hir::Attribute::Unparsed(..) =>
                                                {}
                                                #[deny(unreachable_patterns)]
                                                _ => {}
                                        }
                                    }
                                    None
                                }
                            }
                        } {
                self.tcx.dcx().emit_err(errors::ConstStableNotStable {
                        fn_sig_span: fn_sig.span,
                        const_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_hir::attrs::AttributeKind::*;
                                        let i: &rustc_hir::Attribute = i;
                                        match i {
                                            rustc_hir::Attribute::Parsed(AttributeKind::RustcConstStability {
                                                span, .. }) => {
                                                break 'done Some(*span);
                                            }
                                            rustc_hir::Attribute::Unparsed(..) =>
                                                {}
                                                #[deny(unreachable_patterns)]
                                                _ => {}
                                        }
                                    }
                                    None
                                }
                            }
                        } {
                self.tcx.dcx().emit_err(errors::RustcConstStableIndirectPairing {
                        span,
                    });
            }
        }
    }
}#[instrument(level = "trace", skip(self))]
320    fn check_compatible_stability(&self, def_id: LocalDefId) {
321        if !self.tcx.features().staged_api() {
322            return;
323        }
324
325        let depr = self.tcx.lookup_deprecation_entry(def_id);
326        let stab = self.tcx.lookup_stability(def_id);
327        let const_stab = self.tcx.lookup_const_stability(def_id);
328
329        macro_rules! find_attr_span {
330            ($name:ident) => {{
331                let attrs = self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id));
332                find_attr!(attrs, AttributeKind::$name { span, .. } => *span)
333            }}
334        }
335
336        if stab.is_none()
337            && depr.map_or(false, |d| d.attr.is_since_rustc_version())
338            && let Some(span) = find_attr_span!(Deprecated)
339        {
340            self.tcx.dcx().emit_err(errors::DeprecatedAttribute { span });
341        }
342
343        if let Some(stab) = stab {
344            // Error if prohibited, or can't inherit anything from a container.
345            let kind = annotation_kind(self.tcx, def_id);
346            if kind == AnnotationKind::Prohibited
347                || (kind == AnnotationKind::Container && stab.level.is_stable() && depr.is_some())
348            {
349                if let Some(span) = find_attr_span!(Stability) {
350                    let item_sp = self.tcx.def_span(def_id);
351                    self.tcx.dcx().emit_err(errors::UselessStability { span, item_sp });
352                }
353            }
354
355            // Check if deprecated_since < stable_since. If it is,
356            // this is *almost surely* an accident.
357            if let Some(depr) = depr
358                && let DeprecatedSince::RustcVersion(dep_since) = depr.attr.since
359                && let StabilityLevel::Stable { since: stab_since, .. } = stab.level
360                && let Some(span) = find_attr_span!(Stability)
361            {
362                let item_sp = self.tcx.def_span(def_id);
363                match stab_since {
364                    StableSince::Current => {
365                        self.tcx
366                            .dcx()
367                            .emit_err(errors::CannotStabilizeDeprecated { span, item_sp });
368                    }
369                    StableSince::Version(stab_since) => {
370                        if dep_since < stab_since {
371                            self.tcx
372                                .dcx()
373                                .emit_err(errors::CannotStabilizeDeprecated { span, item_sp });
374                        }
375                    }
376                    StableSince::Err(_) => {
377                        // An error already reported. Assume the unparseable stabilization
378                        // version is older than the deprecation version.
379                    }
380                }
381            }
382        }
383
384        // If the current node is a function with const stability attributes (directly given or
385        // implied), check if the function/method is const or the parent impl block is const.
386        let fn_sig = self.tcx.hir_node_by_def_id(def_id).fn_sig();
387        if let Some(fn_sig) = fn_sig
388            && !fn_sig.header.is_const()
389            && const_stab.is_some()
390            && find_attr_span!(RustcConstStability).is_some()
391        {
392            self.tcx.dcx().emit_err(errors::MissingConstErr { fn_sig_span: fn_sig.span });
393        }
394
395        // If this is marked const *stable*, it must also be regular-stable.
396        if let Some(const_stab) = const_stab
397            && let Some(fn_sig) = fn_sig
398            && const_stab.is_const_stable()
399            && !stab.is_some_and(|s| s.is_stable())
400            && let Some(const_span) = find_attr_span!(RustcConstStability)
401        {
402            self.tcx
403                .dcx()
404                .emit_err(errors::ConstStableNotStable { fn_sig_span: fn_sig.span, const_span });
405        }
406
407        if let Some(stab) = &const_stab
408            && stab.is_const_stable()
409            && stab.const_stable_indirect
410            && let Some(span) = find_attr_span!(RustcConstStability)
411        {
412            self.tcx.dcx().emit_err(errors::RustcConstStableIndirectPairing { span });
413        }
414    }
415
416    #[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(416u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_passes::stability"),
                                    ::tracing_core::field::FieldSet::new(&["def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = 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(errors::MissingStabilityAttr {
                        span,
                        descr,
                    });
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
417    fn check_missing_stability(&self, def_id: LocalDefId) {
418        let stab = self.tcx.lookup_stability(def_id);
419        self.tcx.ensure_ok().lookup_const_stability(def_id);
420        if !self.tcx.sess.is_test_crate()
421            && stab.is_none()
422            && self.effective_visibilities.is_reachable(def_id)
423        {
424            let descr = self.tcx.def_descr(def_id.to_def_id());
425            let span = self.tcx.def_span(def_id);
426            self.tcx.dcx().emit_err(errors::MissingStabilityAttr { span, descr });
427        }
428    }
429
430    fn check_missing_const_stability(&self, def_id: LocalDefId) {
431        let is_const = self.tcx.is_const_fn(def_id.to_def_id())
432            || (self.tcx.def_kind(def_id.to_def_id()) == DefKind::Trait
433                && self.tcx.is_const_trait(def_id.to_def_id()));
434
435        // Reachable const fn/trait must have a stability attribute.
436        if is_const
437            && self.effective_visibilities.is_reachable(def_id)
438            && self.tcx.lookup_const_stability(def_id).is_none()
439        {
440            let span = self.tcx.def_span(def_id);
441            let descr = self.tcx.def_descr(def_id.to_def_id());
442            self.tcx.dcx().emit_err(errors::MissingConstStabAttr { span, descr });
443        }
444    }
445}
446
447impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> {
448    type NestedFilter = nested_filter::OnlyBodies;
449
450    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
451        self.tcx
452    }
453
454    fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
455        self.check_compatible_stability(i.owner_id.def_id);
456
457        // Inherent impls and foreign modules serve only as containers for other items,
458        // they don't have their own stability. They still can be annotated as unstable
459        // and propagate this instability to children, but this annotation is completely
460        // optional. They inherit stability from their parents when unannotated.
461        if !#[allow(non_exhaustive_omitted_patterns)] match i.kind {
    hir::ItemKind::Impl(hir::Impl { of_trait: None, .. }) |
        hir::ItemKind::ForeignMod { .. } => true,
    _ => false,
}matches!(
462            i.kind,
463            hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
464                | hir::ItemKind::ForeignMod { .. }
465        ) {
466            self.check_missing_stability(i.owner_id.def_id);
467        }
468
469        // Ensure stable `const fn` have a const stability attribute.
470        self.check_missing_const_stability(i.owner_id.def_id);
471
472        intravisit::walk_item(self, i)
473    }
474
475    fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
476        self.check_compatible_stability(ti.owner_id.def_id);
477        self.check_missing_stability(ti.owner_id.def_id);
478        intravisit::walk_trait_item(self, ti);
479    }
480
481    fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
482        self.check_compatible_stability(ii.owner_id.def_id);
483        if let hir::ImplItemImplKind::Inherent { .. } = ii.impl_kind {
484            self.check_missing_stability(ii.owner_id.def_id);
485            self.check_missing_const_stability(ii.owner_id.def_id);
486        }
487        intravisit::walk_impl_item(self, ii);
488    }
489
490    fn visit_variant(&mut self, var: &'tcx Variant<'tcx>) {
491        self.check_compatible_stability(var.def_id);
492        self.check_missing_stability(var.def_id);
493        if let Some(ctor_def_id) = var.data.ctor_def_id() {
494            self.check_missing_stability(ctor_def_id);
495        }
496        intravisit::walk_variant(self, var);
497    }
498
499    fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
500        self.check_compatible_stability(s.def_id);
501        self.check_missing_stability(s.def_id);
502        intravisit::walk_field_def(self, s);
503    }
504
505    fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
506        self.check_compatible_stability(i.owner_id.def_id);
507        self.check_missing_stability(i.owner_id.def_id);
508        intravisit::walk_foreign_item(self, i);
509    }
510
511    fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
512        self.check_compatible_stability(p.def_id);
513        // Note that we don't need to `check_missing_stability` for default generic parameters,
514        // as we assume that any default generic parameters without attributes are automatically
515        // stable (assuming they have not inherited instability from their parent).
516        intravisit::walk_generic_param(self, p);
517    }
518}
519
520/// Cross-references the feature names of unstable APIs with enabled
521/// features and possibly prints errors.
522fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
523    tcx.hir_visit_item_likes_in_module(module_def_id, &mut Checker { tcx });
524
525    let is_staged_api =
526        tcx.sess.opts.unstable_opts.force_unstable_if_unmarked || tcx.features().staged_api();
527    if is_staged_api {
528        let effective_visibilities = &tcx.effective_visibilities(());
529        let mut missing = MissingStabilityAnnotations { tcx, effective_visibilities };
530        if module_def_id.is_top_level_module() {
531            missing.check_missing_stability(CRATE_DEF_ID);
532        }
533        tcx.hir_visit_item_likes_in_module(module_def_id, &mut missing);
534    }
535
536    if module_def_id.is_top_level_module() {
537        check_unused_or_stable_features(tcx)
538    }
539}
540
541pub(crate) fn provide(providers: &mut Providers) {
542    *providers = Providers {
543        check_mod_unstable_api_usage,
544        stability_implications,
545        lookup_stability,
546        lookup_const_stability,
547        lookup_default_body_stability,
548        lookup_deprecation_entry,
549        ..*providers
550    };
551}
552
553struct Checker<'tcx> {
554    tcx: TyCtxt<'tcx>,
555}
556
557impl<'tcx> Visitor<'tcx> for Checker<'tcx> {
558    type NestedFilter = nested_filter::OnlyBodies;
559
560    /// Because stability levels are scoped lexically, we want to walk
561    /// nested items in the context of the outer item, so enable
562    /// deep-walking.
563    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
564        self.tcx
565    }
566
567    fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
568        match item.kind {
569            hir::ItemKind::ExternCrate(_, ident) => {
570                // compiler-generated `extern crate` items have a dummy span.
571                // `std` is still checked for the `restricted-std` feature.
572                if item.span.is_dummy() && ident.name != sym::std {
573                    return;
574                }
575
576                let Some(cnum) = self.tcx.extern_mod_stmt_cnum(item.owner_id.def_id) else {
577                    return;
578                };
579                let def_id = cnum.as_def_id();
580                self.tcx.check_stability(def_id, Some(item.hir_id()), item.span, None);
581            }
582
583            // For implementations of traits, check the stability of each item
584            // individually as it's possible to have a stable trait with unstable
585            // items.
586            hir::ItemKind::Impl(hir::Impl {
587                of_trait: Some(of_trait),
588                self_ty,
589                items,
590                constness,
591                ..
592            }) => {
593                let features = self.tcx.features();
594                if features.staged_api() {
595                    let attrs = self.tcx.hir_attrs(item.hir_id());
596                    let stab = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(Stability { stability, span }) =>
                    {
                    break 'done Some((*stability, *span));
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, Stability{stability, span} => (*stability, *span));
597
598                    // FIXME(jdonszelmann): make it impossible to miss the or_else in the typesystem
599                    let const_stab =
600                        {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(RustcConstStability { stability,
                    .. }) => {
                    break 'done Some(*stability);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, RustcConstStability{stability, ..} => *stability);
601
602                    let unstable_feature_stab = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(UnstableFeatureBound(i)) => {
                    break 'done Some(i);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, UnstableFeatureBound(i) => i)
603                        .map(|i| i.as_slice())
604                        .unwrap_or_default();
605
606                    // If this impl block has an #[unstable] attribute, give an
607                    // error if all involved types and traits are stable, because
608                    // it will have no effect.
609                    // See: https://github.com/rust-lang/rust/issues/55436
610                    //
611                    // The exception is when there are both  #[unstable_feature_bound(..)] and
612                    //  #![unstable(feature = "..", issue = "..")] that have the same symbol because
613                    // that can effectively mark an impl as unstable.
614                    //
615                    // For example:
616                    // ```
617                    // #[unstable_feature_bound(feat_foo)]
618                    // #[unstable(feature = "feat_foo", issue = "none")]
619                    // impl Foo for Bar {}
620                    // ```
621                    if let Some((
622                        Stability { level: StabilityLevel::Unstable { .. }, feature },
623                        span,
624                    )) = stab
625                    {
626                        let mut c = CheckTraitImplStable { tcx: self.tcx, fully_stable: true };
627                        c.visit_ty_unambig(self_ty);
628                        c.visit_trait_ref(&of_trait.trait_ref);
629
630                        // Skip the lint if the impl is marked as unstable using
631                        // #[unstable_feature_bound(..)]
632                        let mut unstable_feature_bound_in_effect = false;
633                        for (unstable_bound_feat_name, _) in unstable_feature_stab {
634                            if *unstable_bound_feat_name == feature {
635                                unstable_feature_bound_in_effect = true;
636                            }
637                        }
638
639                        // do not lint when the trait isn't resolved, since resolution error should
640                        // be fixed first
641                        if of_trait.trait_ref.path.res != Res::Err
642                            && c.fully_stable
643                            && !unstable_feature_bound_in_effect
644                        {
645                            self.tcx.emit_node_span_lint(
646                                INEFFECTIVE_UNSTABLE_TRAIT_IMPL,
647                                item.hir_id(),
648                                span,
649                                errors::IneffectiveUnstableImpl,
650                            );
651                        }
652                    }
653
654                    if features.const_trait_impl()
655                        && let hir::Constness::Const = constness
656                    {
657                        let stable_or_implied_stable = match const_stab {
658                            None => true,
659                            Some(stab) if stab.is_const_stable() => {
660                                // `#![feature(const_trait_impl)]` is unstable, so any impl declared stable
661                                // needs to have an error emitted.
662                                // Note: Remove this error once `const_trait_impl` is stabilized
663                                self.tcx
664                                    .dcx()
665                                    .emit_err(errors::TraitImplConstStable { span: item.span });
666                                true
667                            }
668                            Some(_) => false,
669                        };
670
671                        if let Some(trait_id) = of_trait.trait_ref.trait_def_id()
672                            && let Some(const_stab) = self.tcx.lookup_const_stability(trait_id)
673                        {
674                            // the const stability of a trait impl must match the const stability on the trait.
675                            if const_stab.is_const_stable() != stable_or_implied_stable {
676                                let trait_span = self.tcx.def_ident_span(trait_id).unwrap();
677
678                                let impl_stability = if stable_or_implied_stable {
679                                    errors::ImplConstStability::Stable { span: item.span }
680                                } else {
681                                    errors::ImplConstStability::Unstable { span: item.span }
682                                };
683                                let trait_stability = if const_stab.is_const_stable() {
684                                    errors::TraitConstStability::Stable { span: trait_span }
685                                } else {
686                                    errors::TraitConstStability::Unstable { span: trait_span }
687                                };
688
689                                self.tcx.dcx().emit_err(errors::TraitImplConstStabilityMismatch {
690                                    span: item.span,
691                                    impl_stability,
692                                    trait_stability,
693                                });
694                            }
695                        }
696                    }
697                }
698
699                if let hir::Constness::Const = constness
700                    && let Some(def_id) = of_trait.trait_ref.trait_def_id()
701                {
702                    // FIXME(const_trait_impl): Improve the span here.
703                    self.tcx.check_const_stability(
704                        def_id,
705                        of_trait.trait_ref.path.span,
706                        of_trait.trait_ref.path.span,
707                    );
708                }
709
710                for impl_item_ref in items {
711                    let impl_item = self.tcx.associated_item(impl_item_ref.owner_id);
712
713                    if let AssocContainer::TraitImpl(Ok(def_id)) = impl_item.container {
714                        // Pass `None` to skip deprecation warnings.
715                        self.tcx.check_stability(
716                            def_id,
717                            None,
718                            self.tcx.def_span(impl_item_ref.owner_id),
719                            None,
720                        );
721                    }
722                }
723            }
724
725            _ => (/* pass */),
726        }
727        intravisit::walk_item(self, item);
728    }
729
730    fn visit_poly_trait_ref(&mut self, t: &'tcx hir::PolyTraitRef<'tcx>) {
731        match t.modifiers.constness {
732            hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) => {
733                if let Some(def_id) = t.trait_ref.trait_def_id() {
734                    self.tcx.check_const_stability(def_id, t.trait_ref.path.span, span);
735                }
736            }
737            hir::BoundConstness::Never => {}
738        }
739        intravisit::walk_poly_trait_ref(self, t);
740    }
741
742    fn visit_use(&mut self, path: &'tcx UsePath<'tcx>, hir_id: HirId) {
743        let res = path.res;
744
745        // A use item can import something from two namespaces at the same time.
746        // For deprecation/stability we don't want to warn twice.
747        // This specifically happens with constructors for unit/tuple structs.
748        if let Some(ty_ns_res) = res.type_ns
749            && let Some(value_ns_res) = res.value_ns
750            && let Some(type_ns_did) = ty_ns_res.opt_def_id()
751            && let Some(value_ns_did) = value_ns_res.opt_def_id()
752            && let DefKind::Ctor(.., _) = self.tcx.def_kind(value_ns_did)
753            && self.tcx.parent(value_ns_did) == type_ns_did
754        {
755            // Only visit the value namespace path when we've detected a duplicate,
756            // not the type namespace path.
757            let UsePath { segments, res: _, span } = *path;
758            self.visit_path(&Path { segments, res: value_ns_res, span }, hir_id);
759
760            // Though, visit the macro namespace if it exists,
761            // regardless of the checks above relating to constructors.
762            if let Some(res) = res.macro_ns {
763                self.visit_path(&Path { segments, res, span }, hir_id);
764            }
765        } else {
766            // if there's no duplicate, just walk as normal
767            intravisit::walk_use(self, path, hir_id)
768        }
769    }
770
771    fn visit_path(&mut self, path: &hir::Path<'tcx>, id: hir::HirId) {
772        if let Some(def_id) = path.res.opt_def_id() {
773            let method_span = path.segments.last().map(|s| s.ident.span);
774            let item_is_allowed = self.tcx.check_stability_allow_unstable(
775                def_id,
776                Some(id),
777                path.span,
778                method_span,
779                if is_unstable_reexport(self.tcx, id) {
780                    AllowUnstable::Yes
781                } else {
782                    AllowUnstable::No
783                },
784            );
785
786            if item_is_allowed {
787                // The item itself is allowed; check whether the path there is also allowed.
788                let is_allowed_through_unstable_modules: Option<Symbol> =
789                    self.tcx.lookup_stability(def_id).and_then(|stab| match stab.level {
790                        StabilityLevel::Stable { allowed_through_unstable_modules, .. } => {
791                            allowed_through_unstable_modules
792                        }
793                        _ => None,
794                    });
795
796                // Check parent modules stability as well if the item the path refers to is itself
797                // stable. We only emit errors for unstable path segments if the item is stable
798                // or allowed because stability is often inherited, so the most common case is that
799                // both the segments and the item are unstable behind the same feature flag.
800                //
801                // We check here rather than in `visit_path_segment` to prevent visiting the last
802                // path segment twice
803                //
804                // We include special cases via #[rustc_allowed_through_unstable_modules] for items
805                // that were accidentally stabilized through unstable paths before this check was
806                // added, such as `core::intrinsics::transmute`
807                let parents = path.segments.iter().rev().skip(1);
808                for path_segment in parents {
809                    if let Some(def_id) = path_segment.res.opt_def_id() {
810                        match is_allowed_through_unstable_modules {
811                            None => {
812                                // Emit a hard stability error if this path is not stable.
813
814                                // use `None` for id to prevent deprecation check
815                                self.tcx.check_stability_allow_unstable(
816                                    def_id,
817                                    None,
818                                    path.span,
819                                    None,
820                                    if is_unstable_reexport(self.tcx, id) {
821                                        AllowUnstable::Yes
822                                    } else {
823                                        AllowUnstable::No
824                                    },
825                                );
826                            }
827                            Some(deprecation) => {
828                                // Call the stability check directly so that we can control which
829                                // diagnostic is emitted.
830                                let eval_result = self.tcx.eval_stability_allow_unstable(
831                                    def_id,
832                                    None,
833                                    path.span,
834                                    None,
835                                    if is_unstable_reexport(self.tcx, id) {
836                                        AllowUnstable::Yes
837                                    } else {
838                                        AllowUnstable::No
839                                    },
840                                );
841                                let is_allowed = #[allow(non_exhaustive_omitted_patterns)] match eval_result {
    EvalResult::Allow => true,
    _ => false,
}matches!(eval_result, EvalResult::Allow);
842                                if !is_allowed {
843                                    // Calculating message for lint involves calling `self.def_path_str`,
844                                    // which will by default invoke the expensive `visible_parent_map` query.
845                                    // Skip all that work if the lint is allowed anyway.
846                                    if self.tcx.lint_level_at_node(DEPRECATED, id).level
847                                        == lint::Level::Allow
848                                    {
849                                        return;
850                                    }
851                                    // Show a deprecation message.
852                                    let def_path =
853                                        { let _guard = NoTrimmedGuard::new(); self.tcx.def_path_str(def_id) }with_no_trimmed_paths!(self.tcx.def_path_str(def_id));
854                                    let def_kind = self.tcx.def_descr(def_id);
855                                    let diag = Deprecated {
856                                        sub: None,
857                                        kind: def_kind.to_owned(),
858                                        path: def_path,
859                                        note: Some(deprecation),
860                                        since_kind: lint::DeprecatedSinceKind::InEffect,
861                                    };
862                                    self.tcx.emit_node_span_lint(
863                                        DEPRECATED,
864                                        id,
865                                        method_span.unwrap_or(path.span),
866                                        diag,
867                                    );
868                                }
869                            }
870                        }
871                    }
872                }
873            }
874        }
875
876        intravisit::walk_path(self, path)
877    }
878}
879
880/// Check whether a path is a `use` item that has been marked as unstable.
881///
882/// See issue #94972 for details on why this is a special case
883fn is_unstable_reexport(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
884    // Get the LocalDefId so we can lookup the item to check the kind.
885    let Some(owner) = id.as_owner() else {
886        return false;
887    };
888    let def_id = owner.def_id;
889
890    let Some(stab) = tcx.lookup_stability(def_id) else {
891        return false;
892    };
893
894    if stab.level.is_stable() {
895        // The re-export is not marked as unstable, don't override
896        return false;
897    }
898
899    // If this is a path that isn't a use, we don't need to do anything special
900    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(..)) {
901        return false;
902    }
903
904    true
905}
906
907struct CheckTraitImplStable<'tcx> {
908    tcx: TyCtxt<'tcx>,
909    fully_stable: bool,
910}
911
912impl<'tcx> Visitor<'tcx> for CheckTraitImplStable<'tcx> {
913    fn visit_path(&mut self, path: &hir::Path<'tcx>, _id: hir::HirId) {
914        if let Some(def_id) = path.res.opt_def_id()
915            && let Some(stab) = self.tcx.lookup_stability(def_id)
916        {
917            self.fully_stable &= stab.level.is_stable();
918        }
919        intravisit::walk_path(self, path)
920    }
921
922    fn visit_trait_ref(&mut self, t: &'tcx TraitRef<'tcx>) {
923        if let Res::Def(DefKind::Trait, trait_did) = t.path.res {
924            if let Some(stab) = self.tcx.lookup_stability(trait_did) {
925                self.fully_stable &= stab.level.is_stable();
926            }
927        }
928        intravisit::walk_trait_ref(self, t)
929    }
930
931    fn visit_ty(&mut self, t: &'tcx Ty<'tcx, AmbigArg>) {
932        if let TyKind::Never = t.kind {
933            self.fully_stable = false;
934        }
935        if let TyKind::FnPtr(function) = t.kind {
936            if extern_abi_stability(function.abi).is_err() {
937                self.fully_stable = false;
938            }
939        }
940        intravisit::walk_ty(self, t)
941    }
942
943    fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {
944        for ty in fd.inputs {
945            self.visit_ty_unambig(ty)
946        }
947        if let hir::FnRetTy::Return(output_ty) = fd.output {
948            match output_ty.kind {
949                TyKind::Never => {} // `-> !` is stable
950                _ => self.visit_ty_unambig(output_ty),
951            }
952        }
953    }
954}
955
956/// Given the list of enabled features that were not language features (i.e., that
957/// were expected to be library features), and the list of features used from
958/// libraries, identify activated features that don't exist and error about them.
959// This is `pub` for rustdoc. rustc should call it through `check_mod_unstable_api_usage`.
960pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {
961    let _prof_timer = tcx.sess.timer("unused_lib_feature_checking");
962
963    let enabled_lang_features = tcx.features().enabled_lang_features();
964    let mut lang_features = UnordSet::default();
965    for EnabledLangFeature { gate_name, attr_sp, stable_since } in enabled_lang_features {
966        if let Some(version) = stable_since {
967            // Warn if the user has enabled an already-stable lang feature.
968            unnecessary_stable_feature_lint(tcx, *attr_sp, *gate_name, *version);
969        }
970        if !lang_features.insert(gate_name) {
971            // Warn if the user enables a lang feature multiple times.
972            tcx.dcx().emit_err(errors::DuplicateFeatureErr { span: *attr_sp, feature: *gate_name });
973        }
974    }
975
976    let enabled_lib_features = tcx.features().enabled_lib_features();
977    let mut remaining_lib_features = FxIndexMap::default();
978    for EnabledLibFeature { gate_name, attr_sp } in enabled_lib_features {
979        if remaining_lib_features.contains_key(gate_name) {
980            // Warn if the user enables a lib feature multiple times.
981            tcx.dcx().emit_err(errors::DuplicateFeatureErr { span: *attr_sp, feature: *gate_name });
982        }
983        remaining_lib_features.insert(*gate_name, *attr_sp);
984    }
985    // `stdbuild` has special handling for `libc`, so we need to
986    // recognise the feature when building std.
987    // Likewise, libtest is handled specially, so `test` isn't
988    // available as we'd like it to be.
989    // FIXME: only remove `libc` when `stdbuild` is enabled.
990    // FIXME: remove special casing for `test`.
991    // FIXME(#120456) - is `swap_remove` correct?
992    remaining_lib_features.swap_remove(&sym::libc);
993    remaining_lib_features.swap_remove(&sym::test);
994
995    /// For each feature in `defined_features`..
996    ///
997    /// - If it is in `remaining_lib_features` (those features with `#![feature(..)]` attributes in
998    ///   the current crate), check if it is stable (or partially stable) and thus an unnecessary
999    ///   attribute.
1000    /// - If it is in `remaining_implications` (a feature that is referenced by an `implied_by`
1001    ///   from the current crate), then remove it from the remaining implications.
1002    ///
1003    /// Once this function has been invoked for every feature (local crate and all extern crates),
1004    /// then..
1005    ///
1006    /// - If features remain in `remaining_lib_features`, then the user has enabled a feature that
1007    ///   does not exist.
1008    /// - If features remain in `remaining_implications`, the `implied_by` refers to a feature that
1009    ///   does not exist.
1010    ///
1011    /// By structuring the code in this way: checking the features defined from each crate one at a
1012    /// time, less loading from metadata is performed and thus compiler performance is improved.
1013    fn check_features<'tcx>(
1014        tcx: TyCtxt<'tcx>,
1015        remaining_lib_features: &mut FxIndexMap<Symbol, Span>,
1016        remaining_implications: &mut UnordMap<Symbol, Symbol>,
1017        defined_features: &LibFeatures,
1018        all_implications: &UnordMap<Symbol, Symbol>,
1019    ) {
1020        for (feature, stability) in defined_features.to_sorted_vec() {
1021            if let FeatureStability::AcceptedSince(since) = stability
1022                && let Some(span) = remaining_lib_features.get(&feature)
1023            {
1024                // Warn if the user has enabled an already-stable lib feature.
1025                if let Some(implies) = all_implications.get(&feature) {
1026                    unnecessary_partially_stable_feature_lint(tcx, *span, feature, *implies, since);
1027                } else {
1028                    unnecessary_stable_feature_lint(tcx, *span, feature, since);
1029                }
1030            }
1031            // FIXME(#120456) - is `swap_remove` correct?
1032            remaining_lib_features.swap_remove(&feature);
1033
1034            // `feature` is the feature doing the implying, but `implied_by` is the feature with
1035            // the attribute that establishes this relationship. `implied_by` is guaranteed to be a
1036            // feature defined in the local crate because `remaining_implications` is only the
1037            // implications from this crate.
1038            remaining_implications.remove(&feature);
1039
1040            if let FeatureStability::Unstable { old_name: Some(alias) } = stability
1041                && let Some(span) = remaining_lib_features.swap_remove(&alias)
1042            {
1043                tcx.dcx().emit_err(errors::RenamedFeature { span, feature, alias });
1044            }
1045
1046            if remaining_lib_features.is_empty() && remaining_implications.is_empty() {
1047                break;
1048            }
1049        }
1050    }
1051
1052    // All local crate implications need to have the feature that implies it confirmed to exist.
1053    let mut remaining_implications = tcx.stability_implications(LOCAL_CRATE).clone();
1054
1055    // We always collect the lib features enabled in the current crate, even if there are
1056    // no unknown features, because the collection also does feature attribute validation.
1057    let local_defined_features = tcx.lib_features(LOCAL_CRATE);
1058    if !remaining_lib_features.is_empty() || !remaining_implications.is_empty() {
1059        let crates = tcx.crates(());
1060
1061        // Loading the implications of all crates is unavoidable to be able to emit the partial
1062        // stabilization diagnostic, but it can be avoided when there are no
1063        // `remaining_lib_features`.
1064        let mut all_implications = remaining_implications.clone();
1065        for &cnum in crates {
1066            all_implications
1067                .extend_unord(tcx.stability_implications(cnum).items().map(|(k, v)| (*k, *v)));
1068        }
1069
1070        check_features(
1071            tcx,
1072            &mut remaining_lib_features,
1073            &mut remaining_implications,
1074            local_defined_features,
1075            &all_implications,
1076        );
1077
1078        for &cnum in crates {
1079            if remaining_lib_features.is_empty() && remaining_implications.is_empty() {
1080                break;
1081            }
1082            check_features(
1083                tcx,
1084                &mut remaining_lib_features,
1085                &mut remaining_implications,
1086                tcx.lib_features(cnum),
1087                &all_implications,
1088            );
1089        }
1090
1091        if !remaining_lib_features.is_empty() {
1092            let lang_features =
1093                UNSTABLE_LANG_FEATURES.iter().map(|feature| feature.name).collect::<Vec<_>>();
1094            let lib_features = crates
1095                .into_iter()
1096                .flat_map(|&cnum| {
1097                    tcx.lib_features(cnum).stability.keys().copied().into_sorted_stable_ord()
1098                })
1099                .collect::<Vec<_>>();
1100
1101            let valid_feature_names = [lang_features, lib_features].concat();
1102
1103            for (feature, span) in remaining_lib_features {
1104                let suggestion = feature
1105                    .find_similar(&valid_feature_names)
1106                    .map(|(actual_name, _)| errors::MisspelledFeature { span, actual_name });
1107                tcx.dcx().emit_err(errors::UnknownFeature { span, feature, suggestion });
1108            }
1109        }
1110    }
1111
1112    for (&implied_by, &feature) in remaining_implications.to_sorted_stable_ord() {
1113        let local_defined_features = tcx.lib_features(LOCAL_CRATE);
1114        let span = local_defined_features
1115            .stability
1116            .get(&feature)
1117            .expect("feature that implied another does not exist")
1118            .1;
1119        tcx.dcx().emit_err(errors::ImpliedFeatureNotExist { span, feature, implied_by });
1120    }
1121
1122    // FIXME(#44232): the `used_features` table no longer exists, so we
1123    // don't lint about unused features. We should re-enable this one day!
1124}
1125
1126fn unnecessary_partially_stable_feature_lint(
1127    tcx: TyCtxt<'_>,
1128    span: Span,
1129    feature: Symbol,
1130    implies: Symbol,
1131    since: Symbol,
1132) {
1133    tcx.emit_node_span_lint(
1134        lint::builtin::STABLE_FEATURES,
1135        hir::CRATE_HIR_ID,
1136        span,
1137        errors::UnnecessaryPartialStableFeature {
1138            span,
1139            line: tcx.sess.source_map().span_extend_to_line(span),
1140            feature,
1141            since,
1142            implies,
1143        },
1144    );
1145}
1146
1147fn unnecessary_stable_feature_lint(
1148    tcx: TyCtxt<'_>,
1149    span: Span,
1150    feature: Symbol,
1151    mut since: Symbol,
1152) {
1153    if since.as_str() == VERSION_PLACEHOLDER {
1154        since = sym::env_CFG_RELEASE;
1155    }
1156    tcx.emit_node_span_lint(
1157        lint::builtin::STABLE_FEATURES,
1158        hir::CRATE_HIR_ID,
1159        span,
1160        errors::UnnecessaryStableFeature { feature, since },
1161    );
1162}