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