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