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