compiler/rustc_passes/src/stability.rs RUST 1,200 lines View on github.com → Search inside
1//! A pass that annotates every item and method with its stability level,2//! propagating default levels lexically from parent to children ast nodes.34use std::num::NonZero;56use rustc_ast_lowering::stability::extern_abi_stability;7use rustc_data_structures::fx::FxIndexMap;8use rustc_data_structures::unord::{ExtendUnord, UnordMap, UnordSet};9use rustc_feature::{EnabledLangFeature, EnabledLibFeature, UNSTABLE_LANG_FEATURES};10use rustc_hir::attrs::{AttributeKind, DeprecatedSince};11use rustc_hir::def::{DefKind, Res};12use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId, LocalModDefId};13use rustc_hir::intravisit::{self, Visitor, VisitorExt};14use rustc_hir::{15    self as hir, AmbigArg, ConstStability, DefaultBodyStability, FieldDef, HirId, Item, ItemKind,16    Path, Stability, StabilityLevel, StableSince, TraitRef, Ty, TyKind, UnstableReason, UsePath,17    VERSION_PLACEHOLDER, Variant, find_attr,18};19use rustc_middle::hir::nested_filter;20use rustc_middle::middle::lib_features::{FeatureStability, LibFeatures};21use rustc_middle::middle::privacy::EffectiveVisibilities;22use rustc_middle::middle::stability::{AllowUnstable, Deprecated, DeprecationEntry, EvalResult};23use rustc_middle::query::{LocalCrate, Providers};24use rustc_middle::ty::print::with_no_trimmed_paths;25use rustc_middle::ty::{AssocContainer, TyCtxt};26use rustc_session::lint;27use rustc_session::lint::builtin::{DEPRECATED, INEFFECTIVE_UNSTABLE_TRAIT_IMPL};28use rustc_span::{Span, Symbol, sym};29use tracing::instrument;3031use crate::errors;3233#[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}4445fn inherit_deprecation(def_kind: DefKind) -> bool {46    match def_kind {47        DefKind::LifetimeParam | DefKind::TyParam | DefKind::ConstParam => false,48        _ => true,49    }50}5152fn 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::Trait | DefKind::Impl { .. } => true,58                _ => false,59            }60        }61        DefKind::Closure => true,62        _ => false,63    }64}6566fn annotation_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> AnnotationKind {67    let def_kind = tcx.def_kind(def_id);68    match def_kind {69        // Inherent impls and foreign modules serve only as containers for other items,70        // they don't have their own stability. They still can be annotated as unstable71        // and propagate this unstability to children, but this annotation is completely72        // optional. They inherit stability from their parents when unannotated.73        DefKind::Impl { of_trait: false } | DefKind::ForeignMod => AnnotationKind::Container,74        DefKind::Impl { of_trait: true } => AnnotationKind::DeprecationProhibited,7576        // Allow stability attributes on default generic arguments.77        DefKind::TyParam | DefKind::ConstParam => {78            match &tcx.hir_node_by_def_id(def_id).expect_generic_param().kind {79                hir::GenericParamKind::Type { default: Some(_), .. }80                | hir::GenericParamKind::Const { default: Some(_), .. } => {81                    AnnotationKind::Container82                }83                _ => AnnotationKind::Prohibited,84            }85        }8687        // Impl items in trait impls cannot have stability.88        DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst { .. } => {89            match tcx.def_kind(tcx.local_parent(def_id)) {90                DefKind::Impl { of_trait: true } => AnnotationKind::Prohibited,91                _ => AnnotationKind::Required,92            }93        }9495        _ => AnnotationKind::Required,96    }97}9899fn lookup_deprecation_entry(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<DeprecationEntry> {100    let depr = find_attr!(tcx, def_id,101        Deprecated { deprecation, span: _ } => *deprecation102    );103104    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        }110111        return None;112    };113114    // `Deprecation` is just two pointers, no need to intern it115    Some(DeprecationEntry::local(depr, def_id))116}117118fn inherit_stability(def_kind: DefKind) -> bool {119    match def_kind {120        DefKind::Field | DefKind::Variant | DefKind::Ctor(..) => true,121        _ => false,122    }123}124125/// If the `-Z force-unstable-if-unmarked` flag is passed then we provide126/// a parent stability annotation which indicates that this is private127/// with the `rustc_private` feature. This is intended for use when128/// compiling library and `rustc_*` crates themselves so we can leverage crates.io129/// while maintaining the invariant that all sysroot crates are unstable130/// 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        implied_by: None,136        old_name: None,137    },138    feature: sym::rustc_private,139};140141#[instrument(level = "debug", skip(tcx))]142fn lookup_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<Stability> {143    // Propagate unstability. This can happen even for non-staged-api crates in case144    // -Zforce-unstable-if-unmarked is set.145    if !tcx.features().staged_api() {146        if !tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {147            return None;148        }149150        let Some(parent) = tcx.opt_local_parent(def_id) else { return Some(FORCE_UNSTABLE) };151152        if inherit_deprecation(tcx.def_kind(def_id)) {153            let parent = tcx.lookup_stability(parent)?;154            if parent.is_unstable() {155                return Some(parent);156            }157        }158159        return None;160    }161162    // # Regular stability163    let stab = find_attr!(tcx, def_id, Stability { stability, span: _ } => *stability);164165    if let Some(stab) = stab {166        return Some(stab);167    }168169    if inherit_deprecation(tcx.def_kind(def_id)) {170        let Some(parent) = tcx.opt_local_parent(def_id) else {171            return tcx172                .sess173                .opts174                .unstable_opts175                .force_unstable_if_unmarked176                .then_some(FORCE_UNSTABLE);177        };178        let parent = tcx.lookup_stability(parent)?;179        if parent.is_unstable() || inherit_stability(tcx.def_kind(def_id)) {180            return Some(parent);181        }182    }183184    None185}186187#[instrument(level = "debug", skip(tcx))]188fn lookup_default_body_stability(189    tcx: TyCtxt<'_>,190    def_id: LocalDefId,191) -> Option<DefaultBodyStability> {192    if !tcx.features().staged_api() {193        return None;194    }195196    // FIXME: check that this item can have body stability197    find_attr!(tcx, def_id, RustcBodyStability { stability, .. } => *stability)198}199200#[instrument(level = "debug", skip(tcx))]201fn lookup_const_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ConstStability> {202    if !tcx.features().staged_api() {203        // Propagate unstability. This can happen even for non-staged-api crates in case204        // -Zforce-unstable-if-unmarked is set.205        if inherit_deprecation(tcx.def_kind(def_id)) {206            let parent = tcx.opt_local_parent(def_id)?;207            let parent_stab = tcx.lookup_stability(parent)?;208            if parent_stab.is_unstable()209                && let Some(fn_sig) = tcx.hir_node_by_def_id(def_id).fn_sig()210                && fn_sig.header.is_const()211            {212                let const_stable_indirect = find_attr!(tcx, def_id, RustcConstStableIndirect);213                return Some(ConstStability::unmarked(const_stable_indirect, parent_stab));214            }215        }216217        return None;218    }219220    let const_stable_indirect = find_attr!(tcx, def_id, RustcConstStableIndirect);221    let const_stab =222        find_attr!(tcx, def_id, RustcConstStability { stability, span: _ } => *stability);223224    // After checking the immediate attributes, get rid of the span and compute implied225    // const stability: inherit feature gate from regular stability.226    let mut const_stab = const_stab227        .map(|const_stab| ConstStability::from_partial(const_stab, const_stable_indirect));228229    // If this is a const fn but not annotated with stability markers, see if we can inherit230    // regular stability.231    if let Some(fn_sig) = tcx.hir_node_by_def_id(def_id).fn_sig()232        && fn_sig.header.is_const()233        && const_stab.is_none()234        // We only ever inherit unstable features.235        && let Some(inherit_regular_stab) = tcx.lookup_stability(def_id)236        && inherit_regular_stab.is_unstable()237    {238        const_stab = Some(ConstStability {239            // We subject these implicitly-const functions to recursive const stability.240            const_stable_indirect: true,241            promotable: false,242            level: inherit_regular_stab.level,243            feature: inherit_regular_stab.feature,244        });245    }246247    if let Some(const_stab) = const_stab {248        return Some(const_stab);249    }250251    // `impl const Trait for Type` items forward their const stability to their immediate children.252    // FIXME(const_trait_impl): how is this supposed to interact with `#[rustc_const_stable_indirect]`?253    // Currently, once that is set, we do not inherit anything from the parent any more.254    if inherit_const_stability(tcx, def_id) {255        let parent = tcx.opt_local_parent(def_id)?;256        let parent = tcx.lookup_const_stability(parent)?;257        if parent.is_const_unstable() {258            return Some(parent);259        }260    }261262    None263}264265fn stability_implications(tcx: TyCtxt<'_>, LocalCrate: LocalCrate) -> UnordMap<Symbol, Symbol> {266    let mut implications = UnordMap::default();267268    let mut register_implication = |def_id| {269        if let Some(stability) = tcx.lookup_stability(def_id)270            && let StabilityLevel::Unstable { implied_by: Some(implied_by), .. } = stability.level271        {272            implications.insert(implied_by, stability.feature);273        }274275        if let Some(stability) = tcx.lookup_const_stability(def_id)276            && let StabilityLevel::Unstable { implied_by: Some(implied_by), .. } = stability.level277        {278            implications.insert(implied_by, stability.feature);279        }280    };281282    if tcx.features().staged_api() {283        register_implication(CRATE_DEF_ID);284        for def_id in tcx.hir_crate_items(()).definitions() {285            register_implication(def_id);286            let def_kind = tcx.def_kind(def_id);287            if def_kind.is_adt() {288                let adt = tcx.adt_def(def_id);289                for variant in adt.variants() {290                    if variant.def_id != def_id.to_def_id() {291                        register_implication(variant.def_id.expect_local());292                    }293                    for field in &variant.fields {294                        register_implication(field.did.expect_local());295                    }296                    if let Some(ctor_def_id) = variant.ctor_def_id() {297                        register_implication(ctor_def_id.expect_local())298                    }299                }300            }301            if def_kind.has_generics() {302                for param in tcx.generics_of(def_id).own_params.iter() {303                    register_implication(param.def_id.expect_local())304                }305            }306        }307    }308309    implications310}311312struct MissingStabilityAnnotations<'tcx> {313    tcx: TyCtxt<'tcx>,314    effective_visibilities: &'tcx EffectiveVisibilities,315}316317impl<'tcx> MissingStabilityAnnotations<'tcx> {318    /// Verify that deprecation and stability attributes make sense with one another.319    #[instrument(level = "trace", skip(self))]320    fn check_compatible_stability(&self, def_id: LocalDefId) {321        if !self.tcx.features().staged_api() {322            return;323        }324325        let depr = self.tcx.lookup_deprecation_entry(def_id);326        let stab = self.tcx.lookup_stability(def_id);327        let const_stab = self.tcx.lookup_const_stability(def_id);328329        macro_rules! find_attr_span {330            ($name:ident) => {{331                let attrs = self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id));332                find_attr!(attrs, AttributeKind::$name { span, .. } => *span)333            }}334        }335336        if stab.is_none()337            && depr.map_or(false, |d| d.attr.is_since_rustc_version())338            && let Some(span) = find_attr_span!(Deprecated)339        {340            self.tcx.dcx().emit_err(errors::DeprecatedAttribute { span });341        }342343        if let Some(stab) = stab {344            // Error if prohibited, or can't inherit anything from a container.345            let kind = annotation_kind(self.tcx, def_id);346            if kind == AnnotationKind::Prohibited347                || (kind == AnnotationKind::Container && stab.level.is_stable() && depr.is_some())348            {349                if let Some(span) = find_attr_span!(Stability) {350                    let item_sp = self.tcx.def_span(def_id);351                    self.tcx.dcx().emit_err(errors::UselessStability { span, item_sp });352                }353            }354355            // Check if deprecated_since < stable_since. If it is,356            // this is *almost surely* an accident.357            if let Some(depr) = depr358                && let DeprecatedSince::RustcVersion(dep_since) = depr.attr.since359                && let StabilityLevel::Stable { since: stab_since, .. } = stab.level360                && let Some(span) = find_attr_span!(Stability)361            {362                let item_sp = self.tcx.def_span(def_id);363                match stab_since {364                    StableSince::Current => {365                        self.tcx366                            .dcx()367                            .emit_err(errors::CannotStabilizeDeprecated { span, item_sp });368                    }369                    StableSince::Version(stab_since) => {370                        if dep_since < stab_since {371                            self.tcx372                                .dcx()373                                .emit_err(errors::CannotStabilizeDeprecated { span, item_sp });374                        }375                    }376                    StableSince::Err(_) => {377                        // An error already reported. Assume the unparseable stabilization378                        // version is older than the deprecation version.379                    }380                }381            }382        }383384        // If the current node is a function with const stability attributes (directly given or385        // implied), check if the function/method is const or the parent impl block is const.386        let fn_sig = self.tcx.hir_node_by_def_id(def_id).fn_sig();387        if let Some(fn_sig) = fn_sig388            && !fn_sig.header.is_const()389            && const_stab.is_some()390            && find_attr_span!(RustcConstStability).is_some()391        {392            self.tcx.dcx().emit_err(errors::MissingConstErr { fn_sig_span: fn_sig.span });393        }394395        // If this is marked const *stable*, it must also be regular-stable.396        if let Some(const_stab) = const_stab397            && let Some(fn_sig) = fn_sig398            && const_stab.is_const_stable()399            && !stab.is_some_and(|s| s.is_stable())400            && let Some(const_span) = find_attr_span!(RustcConstStability)401        {402            self.tcx403                .dcx()404                .emit_err(errors::ConstStableNotStable { fn_sig_span: fn_sig.span, const_span });405        }406407        if let Some(stab) = &const_stab408            && stab.is_const_stable()409            && stab.const_stable_indirect410            && let Some(span) = find_attr_span!(RustcConstStability)411        {412            self.tcx.dcx().emit_err(errors::RustcConstStableIndirectPairing { span });413        }414    }415416    #[instrument(level = "debug", skip(self))]417    fn check_missing_stability(&self, def_id: LocalDefId) {418        let stab = self.tcx.lookup_stability(def_id);419        self.tcx.ensure_ok().lookup_const_stability(def_id);420        if !self.tcx.sess.is_test_crate()421            && stab.is_none()422            && self.effective_visibilities.is_reachable(def_id)423        {424            let descr = self.tcx.def_descr(def_id.to_def_id());425            let span = self.tcx.def_span(def_id);426            self.tcx.dcx().emit_err(errors::MissingStabilityAttr { span, descr });427        }428    }429430    fn check_missing_const_stability(&self, def_id: LocalDefId) {431        let is_const = self.tcx.is_const_fn(def_id.to_def_id())432            || (self.tcx.def_kind(def_id.to_def_id()) == DefKind::Trait433                && self.tcx.is_const_trait(def_id.to_def_id()));434435        // Reachable const fn/trait must have a stability attribute.436        if is_const437            && self.effective_visibilities.is_reachable(def_id)438            && self.tcx.lookup_const_stability(def_id).is_none()439        {440            let span = self.tcx.def_span(def_id);441            let descr = self.tcx.def_descr(def_id.to_def_id());442            self.tcx.dcx().emit_err(errors::MissingConstStabAttr { span, descr });443        }444    }445}446447impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> {448    type NestedFilter = nested_filter::OnlyBodies;449450    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {451        self.tcx452    }453454    fn visit_item(&mut self, i: &'tcx Item<'tcx>) {455        self.check_compatible_stability(i.owner_id.def_id);456457        // Inherent impls and foreign modules serve only as containers for other items,458        // they don't have their own stability. They still can be annotated as unstable459        // and propagate this instability to children, but this annotation is completely460        // optional. They inherit stability from their parents when unannotated.461        if !matches!(462            i.kind,463            hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })464                | hir::ItemKind::ForeignMod { .. }465        ) {466            self.check_missing_stability(i.owner_id.def_id);467        }468469        // Ensure stable `const fn` have a const stability attribute.470        self.check_missing_const_stability(i.owner_id.def_id);471472        intravisit::walk_item(self, i)473    }474475    fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {476        self.check_compatible_stability(ti.owner_id.def_id);477        self.check_missing_stability(ti.owner_id.def_id);478        intravisit::walk_trait_item(self, ti);479    }480481    fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {482        self.check_compatible_stability(ii.owner_id.def_id);483        if let hir::ImplItemImplKind::Inherent { .. } = ii.impl_kind {484            self.check_missing_stability(ii.owner_id.def_id);485            self.check_missing_const_stability(ii.owner_id.def_id);486        }487        intravisit::walk_impl_item(self, ii);488    }489490    fn visit_variant(&mut self, var: &'tcx Variant<'tcx>) {491        self.check_compatible_stability(var.def_id);492        self.check_missing_stability(var.def_id);493        if let Some(ctor_def_id) = var.data.ctor_def_id() {494            self.check_missing_stability(ctor_def_id);495        }496        intravisit::walk_variant(self, var);497    }498499    fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {500        self.check_compatible_stability(s.def_id);501        self.check_missing_stability(s.def_id);502        intravisit::walk_field_def(self, s);503    }504505    fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {506        self.check_compatible_stability(i.owner_id.def_id);507        self.check_missing_stability(i.owner_id.def_id);508        intravisit::walk_foreign_item(self, i);509    }510511    fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {512        self.check_compatible_stability(p.def_id);513        // Note that we don't need to `check_missing_stability` for default generic parameters,514        // as we assume that any default generic parameters without attributes are automatically515        // stable (assuming they have not inherited instability from their parent).516        intravisit::walk_generic_param(self, p);517    }518}519520/// Cross-references the feature names of unstable APIs with enabled521/// features and possibly prints errors.522fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {523    tcx.hir_visit_item_likes_in_module(module_def_id, &mut Checker { tcx });524525    let is_staged_api =526        tcx.sess.opts.unstable_opts.force_unstable_if_unmarked || tcx.features().staged_api();527    if is_staged_api {528        let effective_visibilities = &tcx.effective_visibilities(());529        let mut missing = MissingStabilityAnnotations { tcx, effective_visibilities };530        if module_def_id.is_top_level_module() {531            missing.check_missing_stability(CRATE_DEF_ID);532        }533        tcx.hir_visit_item_likes_in_module(module_def_id, &mut missing);534    }535536    if module_def_id.is_top_level_module() {537        check_unused_or_stable_features(tcx)538    }539}540541pub(crate) fn provide(providers: &mut Providers) {542    *providers = Providers {543        check_mod_unstable_api_usage,544        stability_implications,545        lookup_stability,546        lookup_const_stability,547        lookup_default_body_stability,548        lookup_deprecation_entry,549        ..*providers550    };551}552553struct Checker<'tcx> {554    tcx: TyCtxt<'tcx>,555}556557impl<'tcx> Visitor<'tcx> for Checker<'tcx> {558    type NestedFilter = nested_filter::OnlyBodies;559560    /// Because stability levels are scoped lexically, we want to walk561    /// nested items in the context of the outer item, so enable562    /// deep-walking.563    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {564        self.tcx565    }566567    fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {568        match item.kind {569            hir::ItemKind::ExternCrate(_, ident) => {570                // compiler-generated `extern crate` items have a dummy span.571                // `std` is still checked for the `restricted-std` feature.572                if item.span.is_dummy() && ident.name != sym::std {573                    return;574                }575576                let Some(cnum) = self.tcx.extern_mod_stmt_cnum(item.owner_id.def_id) else {577                    return;578                };579                let def_id = cnum.as_def_id();580                self.tcx.check_stability(def_id, Some(item.hir_id()), item.span, None);581            }582583            // For implementations of traits, check the stability of each item584            // individually as it's possible to have a stable trait with unstable585            // items.586            hir::ItemKind::Impl(hir::Impl {587                of_trait: Some(of_trait),588                self_ty,589                items,590                constness,591                ..592            }) => {593                let features = self.tcx.features();594                if features.staged_api() {595                    let attrs = self.tcx.hir_attrs(item.hir_id());596                    let stab = find_attr!(attrs, Stability{stability, span} => (*stability, *span));597598                    // FIXME(jdonszelmann): make it impossible to miss the or_else in the typesystem599                    let const_stab =600                        find_attr!(attrs, RustcConstStability{stability, ..} => *stability);601602                    let unstable_feature_stab = find_attr!(attrs, UnstableFeatureBound(i) => i)603                        .map(|i| i.as_slice())604                        .unwrap_or_default();605606                    // If this impl block has an #[unstable] attribute, give an607                    // error if all involved types and traits are stable, because608                    // it will have no effect.609                    // See: https://github.com/rust-lang/rust/issues/55436610                    //611                    // The exception is when there are both  #[unstable_feature_bound(..)] and612                    //  #![unstable(feature = "..", issue = "..")] that have the same symbol because613                    // 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                    )) = stab625                    {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);629630                        // Skip the lint if the impl is marked as unstable using631                        // #[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                        }638639                        // do not lint when the trait isn't resolved, since resolution error should640                        // be fixed first641                        if of_trait.trait_ref.path.res != Res::Err642                            && c.fully_stable643                            && !unstable_feature_bound_in_effect644                        {645                            self.tcx.emit_node_span_lint(646                                INEFFECTIVE_UNSTABLE_TRAIT_IMPL,647                                item.hir_id(),648                                span,649                                errors::IneffectiveUnstableImpl,650                            );651                        }652                    }653654                    if features.const_trait_impl()655                        && let hir::Constness::Const = constness656                    {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 stable661                                // needs to have an error emitted.662                                // Note: Remove this error once `const_trait_impl` is stabilized663                                self.tcx664                                    .dcx()665                                    .emit_err(errors::TraitImplConstStable { span: item.span });666                                true667                            }668                            Some(_) => false,669                        };670671                        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();677678                                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                                };688689                                self.tcx.dcx().emit_err(errors::TraitImplConstStabilityMismatch {690                                    span: item.span,691                                    impl_stability,692                                    trait_stability,693                                });694                            }695                        }696                    }697                }698699                if let hir::Constness::Const = constness700                    && 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                }709710                for impl_item_ref in items {711                    let impl_item = self.tcx.associated_item(impl_item_ref.owner_id);712713                    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            }724725            _ => (/* pass */),726        }727        intravisit::walk_item(self, item);728    }729730    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    }741742    fn visit_use(&mut self, path: &'tcx UsePath<'tcx>, hir_id: HirId) {743        let res = path.res;744745        // A use item can import something from two namespaces at the same time.746        // For deprecation/stability we don't want to warn twice.747        // This specifically happens with constructors for unit/tuple structs.748        if let Some(ty_ns_res) = res.type_ns749            && let Some(value_ns_res) = res.value_ns750            && let Some(type_ns_did) = ty_ns_res.opt_def_id()751            && let Some(value_ns_did) = value_ns_res.opt_def_id()752            && let DefKind::Ctor(.., _) = self.tcx.def_kind(value_ns_did)753            && self.tcx.parent(value_ns_did) == type_ns_did754        {755            // Only visit the value namespace path when we've detected a duplicate,756            // not the type namespace path.757            let UsePath { segments, res: _, span } = *path;758            self.visit_path(&Path { segments, res: value_ns_res, span }, hir_id);759760            // Though, visit the macro namespace if it exists,761            // regardless of the checks above relating to constructors.762            if let Some(res) = res.macro_ns {763                self.visit_path(&Path { segments, res, span }, hir_id);764            }765        } else {766            // if there's no duplicate, just walk as normal767            intravisit::walk_use(self, path, hir_id)768        }769    }770771    fn visit_path(&mut self, path: &hir::Path<'tcx>, id: hir::HirId) {772        if let Some(def_id) = path.res.opt_def_id() {773            let method_span = path.segments.last().map(|s| s.ident.span);774            let item_is_allowed = self.tcx.check_stability_allow_unstable(775                def_id,776                Some(id),777                path.span,778                method_span,779                if is_unstable_reexport(self.tcx, id) {780                    AllowUnstable::Yes781                } else {782                    AllowUnstable::No783                },784            );785786            if item_is_allowed {787                // The item itself is allowed; check whether the path there is also allowed.788                let is_allowed_through_unstable_modules: Option<Symbol> =789                    self.tcx.lookup_stability(def_id).and_then(|stab| match stab.level {790                        StabilityLevel::Stable { allowed_through_unstable_modules, .. } => {791                            allowed_through_unstable_modules792                        }793                        _ => None,794                    });795796                // Check parent modules stability as well if the item the path refers to is itself797                // stable. We only emit errors for unstable path segments if the item is stable798                // or allowed because stability is often inherited, so the most common case is that799                // both the segments and the item are unstable behind the same feature flag.800                //801                // We check here rather than in `visit_path_segment` to prevent visiting the last802                // path segment twice803                //804                // We include special cases via #[rustc_allowed_through_unstable_modules] for items805                // that were accidentally stabilized through unstable paths before this check was806                // added, such as `core::intrinsics::transmute`807                let parents = path.segments.iter().rev().skip(1);808                for path_segment in parents {809                    if let Some(def_id) = path_segment.res.opt_def_id() {810                        match is_allowed_through_unstable_modules {811                            None => {812                                // Emit a hard stability error if this path is not stable.813814                                // use `None` for id to prevent deprecation check815                                self.tcx.check_stability_allow_unstable(816                                    def_id,817                                    None,818                                    path.span,819                                    None,820                                    if is_unstable_reexport(self.tcx, id) {821                                        AllowUnstable::Yes822                                    } else {823                                        AllowUnstable::No824                                    },825                                );826                            }827                            Some(deprecation) => {828                                // Call the stability check directly so that we can control which829                                // diagnostic is emitted.830                                let eval_result = self.tcx.eval_stability_allow_unstable(831                                    def_id,832                                    None,833                                    path.span,834                                    None,835                                    if is_unstable_reexport(self.tcx, id) {836                                        AllowUnstable::Yes837                                    } else {838                                        AllowUnstable::No839                                    },840                                );841                                let is_allowed = matches!(eval_result, EvalResult::Allow);842                                if !is_allowed {843                                    // Calculating message for lint involves calling `self.def_path_str`,844                                    // which will by default invoke the expensive `visible_parent_map` query.845                                    // Skip all that work if the lint is allowed anyway.846                                    if self.tcx.lint_level_at_node(DEPRECATED, id).level847                                        == lint::Level::Allow848                                    {849                                        return;850                                    }851                                    // Show a deprecation message.852                                    let def_path =853                                        with_no_trimmed_paths!(self.tcx.def_path_str(def_id));854                                    let def_kind = self.tcx.def_descr(def_id);855                                    let diag = Deprecated {856                                        sub: None,857                                        kind: def_kind.to_owned(),858                                        path: def_path,859                                        note: Some(deprecation),860                                        since_kind: lint::DeprecatedSinceKind::InEffect,861                                    };862                                    self.tcx.emit_node_span_lint(863                                        DEPRECATED,864                                        id,865                                        method_span.unwrap_or(path.span),866                                        diag,867                                    );868                                }869                            }870                        }871                    }872                }873            }874        }875876        intravisit::walk_path(self, path)877    }878}879880/// Check whether a path is a `use` item that has been marked as unstable.881///882/// See issue #94972 for details on why this is a special case883fn is_unstable_reexport(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {884    // Get the LocalDefId so we can lookup the item to check the kind.885    let Some(owner) = id.as_owner() else {886        return false;887    };888    let def_id = owner.def_id;889890    let Some(stab) = tcx.lookup_stability(def_id) else {891        return false;892    };893894    if stab.level.is_stable() {895        // The re-export is not marked as unstable, don't override896        return false;897    }898899    // If this is a path that isn't a use, we don't need to do anything special900    if !matches!(tcx.hir_expect_item(def_id).kind, ItemKind::Use(..)) {901        return false;902    }903904    true905}906907struct CheckTraitImplStable<'tcx> {908    tcx: TyCtxt<'tcx>,909    fully_stable: bool,910}911912impl<'tcx> Visitor<'tcx> for CheckTraitImplStable<'tcx> {913    fn visit_path(&mut self, path: &hir::Path<'tcx>, _id: hir::HirId) {914        if let Some(def_id) = path.res.opt_def_id()915            && let Some(stab) = self.tcx.lookup_stability(def_id)916        {917            self.fully_stable &= stab.level.is_stable();918        }919        intravisit::walk_path(self, path)920    }921922    fn visit_trait_ref(&mut self, t: &'tcx TraitRef<'tcx>) {923        if let Res::Def(DefKind::Trait, trait_did) = t.path.res {924            if let Some(stab) = self.tcx.lookup_stability(trait_did) {925                self.fully_stable &= stab.level.is_stable();926            }927        }928        intravisit::walk_trait_ref(self, t)929    }930931    fn visit_ty(&mut self, t: &'tcx Ty<'tcx, AmbigArg>) {932        if let TyKind::Never = t.kind {933            self.fully_stable = false;934        }935        if let TyKind::FnPtr(function) = t.kind {936            if extern_abi_stability(function.abi).is_err() {937                self.fully_stable = false;938            }939        }940        intravisit::walk_ty(self, t)941    }942943    fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {944        for ty in fd.inputs {945            self.visit_ty_unambig(ty)946        }947        if let hir::FnRetTy::Return(output_ty) = fd.output {948            match output_ty.kind {949                TyKind::Never => {} // `-> !` is stable950                _ => self.visit_ty_unambig(output_ty),951            }952        }953    }954}955956/// Given the list of enabled features that were not language features (i.e., that957/// were expected to be library features), and the list of features used from958/// libraries, identify activated features that don't exist and error about them.959// This is `pub` for rustdoc. rustc should call it through `check_mod_unstable_api_usage`.960pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {961    let _prof_timer = tcx.sess.timer("unused_lib_feature_checking");962963    let enabled_lang_features = tcx.features().enabled_lang_features();964    let mut lang_features = UnordSet::default();965    for EnabledLangFeature { gate_name, attr_sp, stable_since } in enabled_lang_features {966        if let Some(version) = stable_since {967            // Mark the feature as enabled, to ensure that it is not marked as unused.968            let _ = tcx.features().enabled(*gate_name);969970            // Warn if the user has enabled an already-stable lang feature.971            unnecessary_stable_feature_lint(tcx, *attr_sp, *gate_name, *version);972        }973        if !lang_features.insert(gate_name) {974            // Warn if the user enables a lang feature multiple times.975            duplicate_feature_lint(tcx, *attr_sp, *gate_name);976        }977    }978979    let enabled_lib_features = tcx.features().enabled_lib_features();980    let mut remaining_lib_features = FxIndexMap::default();981    for EnabledLibFeature { gate_name, attr_sp } in enabled_lib_features {982        if remaining_lib_features.contains_key(gate_name) {983            // Warn if the user enables a lib feature multiple times.984            duplicate_feature_lint(tcx, *attr_sp, *gate_name);985        }986        remaining_lib_features.insert(*gate_name, *attr_sp);987    }988    // `stdbuild` has special handling for `libc`, so we need to989    // recognise the feature when building std.990    // Likewise, libtest is handled specially, so `test` isn't991    // available as we'd like it to be.992    // FIXME: only remove `libc` when `stdbuild` is enabled.993    // FIXME: remove special casing for `test`.994    // FIXME(#120456) - is `swap_remove` correct?995    remaining_lib_features.swap_remove(&sym::libc);996    remaining_lib_features.swap_remove(&sym::test);997998    /// For each feature in `defined_features`..999    ///1000    /// - If it is in `remaining_lib_features` (those features with `#![feature(..)]` attributes in1001    ///   the current crate), check if it is stable (or partially stable) and thus an unnecessary1002    ///   attribute.1003    /// - If it is in `remaining_implications` (a feature that is referenced by an `implied_by`1004    ///   from the current crate), then remove it from the remaining implications.1005    ///1006    /// Once this function has been invoked for every feature (local crate and all extern crates),1007    /// then..1008    ///1009    /// - If features remain in `remaining_lib_features`, then the user has enabled a feature that1010    ///   does not exist.1011    /// - If features remain in `remaining_implications`, the `implied_by` refers to a feature that1012    ///   does not exist.1013    ///1014    /// By structuring the code in this way: checking the features defined from each crate one at a1015    /// time, less loading from metadata is performed and thus compiler performance is improved.1016    fn check_features<'tcx>(1017        tcx: TyCtxt<'tcx>,1018        remaining_lib_features: &mut FxIndexMap<Symbol, Span>,1019        remaining_implications: &mut UnordMap<Symbol, Symbol>,1020        defined_features: &LibFeatures,1021        all_implications: &UnordMap<Symbol, Symbol>,1022    ) {1023        for (feature, stability) in defined_features.to_sorted_vec() {1024            if let FeatureStability::AcceptedSince(since) = stability1025                && let Some(span) = remaining_lib_features.get(&feature)1026            {1027                // Mark the feature as enabled, to ensure that it is not marked as unused.1028                let _ = tcx.features().enabled(feature);10291030                // Warn if the user has enabled an already-stable lib feature.1031                if let Some(implies) = all_implications.get(&feature) {1032                    unnecessary_partially_stable_feature_lint(tcx, *span, feature, *implies, since);1033                } else {1034                    unnecessary_stable_feature_lint(tcx, *span, feature, since);1035                }1036            }1037            // FIXME(#120456) - is `swap_remove` correct?1038            remaining_lib_features.swap_remove(&feature);10391040            // `feature` is the feature doing the implying, but `implied_by` is the feature with1041            // the attribute that establishes this relationship. `implied_by` is guaranteed to be a1042            // feature defined in the local crate because `remaining_implications` is only the1043            // implications from this crate.1044            remaining_implications.remove(&feature);10451046            if let FeatureStability::Unstable { old_name: Some(alias) } = stability1047                && let Some(span) = remaining_lib_features.swap_remove(&alias)1048            {1049                tcx.dcx().emit_err(errors::RenamedFeature { span, feature, alias });1050            }10511052            if remaining_lib_features.is_empty() && remaining_implications.is_empty() {1053                break;1054            }1055        }1056    }10571058    // All local crate implications need to have the feature that implies it confirmed to exist.1059    let mut remaining_implications = tcx.stability_implications(LOCAL_CRATE).clone();10601061    // We always collect the lib features enabled in the current crate, even if there are1062    // no unknown features, because the collection also does feature attribute validation.1063    let local_defined_features = tcx.lib_features(LOCAL_CRATE);1064    if !remaining_lib_features.is_empty() || !remaining_implications.is_empty() {1065        let crates = tcx.crates(());10661067        // Loading the implications of all crates is unavoidable to be able to emit the partial1068        // stabilization diagnostic, but it can be avoided when there are no1069        // `remaining_lib_features`.1070        let mut all_implications = remaining_implications.clone();1071        for &cnum in crates {1072            all_implications1073                .extend_unord(tcx.stability_implications(cnum).items().map(|(k, v)| (*k, *v)));1074        }10751076        check_features(1077            tcx,1078            &mut remaining_lib_features,1079            &mut remaining_implications,1080            local_defined_features,1081            &all_implications,1082        );10831084        for &cnum in crates {1085            if remaining_lib_features.is_empty() && remaining_implications.is_empty() {1086                break;1087            }1088            check_features(1089                tcx,1090                &mut remaining_lib_features,1091                &mut remaining_implications,1092                tcx.lib_features(cnum),1093                &all_implications,1094            );1095        }10961097        if !remaining_lib_features.is_empty() {1098            let lang_features =1099                UNSTABLE_LANG_FEATURES.iter().map(|feature| feature.name).collect::<Vec<_>>();1100            let lib_features = crates1101                .iter()1102                .flat_map(|&cnum| {1103                    tcx.lib_features(cnum).stability.keys().copied().into_sorted_stable_ord()1104                })1105                .collect::<Vec<_>>();11061107            let valid_feature_names = [lang_features, lib_features].concat();11081109            // Collect all of the marked as "removed" features1110            let unstable_removed_features = crates1111                .iter()1112                .flat_map(|&cnum| {1113                    find_attr!(tcx, cnum.as_def_id(), UnstableRemoved(rem_features) => rem_features)1114                        .into_iter()1115                        .flatten()1116                })1117                .collect::<Vec<_>>();11181119            for (feature, span) in remaining_lib_features {1120                if let Some(removed) =1121                    unstable_removed_features.iter().find(|removed| removed.feature == feature)1122                {1123                    tcx.dcx().emit_err(errors::FeatureRemoved {1124                        span,1125                        feature,1126                        reason: removed.reason,1127                        link: removed.link,1128                        since: removed.since.to_string(),1129                    });1130                } else {1131                    let suggestion = feature1132                        .find_similar(&valid_feature_names)1133                        .map(|(actual_name, _)| errors::MisspelledFeature { span, actual_name });1134                    tcx.dcx().emit_err(errors::UnknownFeature { span, feature, suggestion });1135                }1136            }1137        }1138    }11391140    for (&implied_by, &feature) in remaining_implications.to_sorted_stable_ord() {1141        let local_defined_features = tcx.lib_features(LOCAL_CRATE);1142        let span = local_defined_features1143            .stability1144            .get(&feature)1145            .expect("feature that implied another does not exist")1146            .1;1147        tcx.dcx().emit_err(errors::ImpliedFeatureNotExist { span, feature, implied_by });1148    }11491150    // FIXME(#44232): the `used_features` table no longer exists, so we1151    // don't lint about unused features. We should re-enable this one day!1152}11531154fn unnecessary_partially_stable_feature_lint(1155    tcx: TyCtxt<'_>,1156    span: Span,1157    feature: Symbol,1158    implies: Symbol,1159    since: Symbol,1160) {1161    tcx.emit_node_span_lint(1162        lint::builtin::STABLE_FEATURES,1163        hir::CRATE_HIR_ID,1164        span,1165        errors::UnnecessaryPartialStableFeature {1166            span,1167            line: tcx.sess.source_map().span_extend_to_line(span),1168            feature,1169            since,1170            implies,1171        },1172    );1173}11741175fn unnecessary_stable_feature_lint(1176    tcx: TyCtxt<'_>,1177    span: Span,1178    feature: Symbol,1179    mut since: Symbol,1180) {1181    if since.as_str() == VERSION_PLACEHOLDER {1182        since = sym::env_CFG_RELEASE;1183    }1184    tcx.emit_node_span_lint(1185        lint::builtin::STABLE_FEATURES,1186        hir::CRATE_HIR_ID,1187        span,1188        errors::UnnecessaryStableFeature { feature, since },1189    );1190}11911192fn duplicate_feature_lint(tcx: TyCtxt<'_>, span: Span, feature: Symbol) {1193    tcx.emit_node_span_lint(1194        lint::builtin::DUPLICATE_FEATURES,1195        hir::CRATE_HIR_ID,1196        span,1197        errors::DuplicateFeature { feature },1198    );1199}

Code quality findings 14

Warning: '.unwrap()' will panic on None/Err variants. Prefer using pattern matching (match, if let), combinators (map, and_then), or the '?' operator for robust error handling.
warning correctness unwrap-usage
let trait_span = self.tcx.def_ident_span(trait_id).unwrap();
Warning: Ignoring a Result or Option using 'let _ =' can hide errors or unexpected None values. Ensure the value is handled appropriately (match, if let, ?, expect) unless intentionally discarded with justification.
warning correctness discarded-result
let _ = tcx.features().enabled(*gate_name);
Warning: Ignoring a Result or Option using 'let _ =' can hide errors or unexpected None values. Ensure the value is handled appropriately (match, if let, ?, expect) unless intentionally discarded with justification.
warning correctness discarded-result
let _ = tcx.features().enabled(feature);
Warning: '.expect()' will panic with a custom message on None/Err. While better than unwrap() for debugging, prefer non-panicking error handling in production code (match, if let, ?).
warning correctness expect-usage
.expect("feature that implied another does not exist")
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
match def_kind {
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
match def_kind {
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
match tcx.def_kind(tcx.local_parent(def_id)) {
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
match &tcx.hir_node_by_def_id(def_id).expect_generic_param().kind {
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
match tcx.def_kind(tcx.local_parent(def_id)) {
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
match def_kind {
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
self.tcx.lookup_stability(def_id).and_then(|stab| match stab.level {
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
match output_ty.kind {
Performance Info: Frequent cloning, especially of Strings, Vecs, or other heap-allocated types inside loops, can be expensive. Consider using references/borrowing where possible.
info performance clone-in-loop
let mut all_implications = remaining_implications.clone();
Performance Info: Calling .to_string() (especially on &str) allocates a new String. If done repeatedly in loops, consider alternatives like working with &str or using crates like `itoa`/`ryu` for number-to-string conversion.
info performance to-string-in-loop
since: removed.since.to_string(),

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.