compiler/rustc_passes/src/stability.rs RUST 1,202 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, Constness, DefaultBodyStability, FieldDef, HirId, Item,16    ItemKind, Path, Stability, StabilityLevel, StableSince, TraitRef, Ty, TyKind, UnstableReason,17    UsePath, 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::diagnostics;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                && matches!(fn_sig.header.constness, Constness::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        && matches!(fn_sig.header.constness, Constness::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(diagnostics::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(diagnostics::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(diagnostics::CannotStabilizeDeprecated { span, item_sp });368                    }369                    StableSince::Version(stab_since) => {370                        if dep_since < stab_since {371                            self.tcx372                                .dcx()373                                .emit_err(diagnostics::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            && !matches!(fn_sig.header.constness, Constness::Const { .. })389            && const_stab.is_some()390            && find_attr_span!(RustcConstStability).is_some()391        {392            self.tcx.dcx().emit_err(diagnostics::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.tcx.dcx().emit_err(diagnostics::ConstStableNotStable {403                fn_sig_span: fn_sig.span,404                const_span,405            });406        }407408        if let Some(stab) = &const_stab409            && stab.is_const_stable()410            && stab.const_stable_indirect411            && let Some(span) = find_attr_span!(RustcConstStability)412        {413            self.tcx.dcx().emit_err(diagnostics::RustcConstStableIndirectPairing { span });414        }415    }416417    #[instrument(level = "debug", skip(self))]418    fn check_missing_stability(&self, def_id: LocalDefId) {419        let stab = self.tcx.lookup_stability(def_id);420        self.tcx.ensure_ok().lookup_const_stability(def_id);421        if !self.tcx.sess.is_test_crate()422            && stab.is_none()423            && self.effective_visibilities.is_reachable(def_id)424        {425            let descr = self.tcx.def_descr(def_id.to_def_id());426            let span = self.tcx.def_span(def_id);427            self.tcx.dcx().emit_err(diagnostics::MissingStabilityAttr { span, descr });428        }429    }430431    fn check_missing_const_stability(&self, def_id: LocalDefId) {432        let is_const = self.tcx.is_const_fn(def_id.to_def_id())433            || (self.tcx.def_kind(def_id.to_def_id()) == DefKind::Trait434                && self.tcx.is_const_trait(def_id.to_def_id()));435436        // Reachable const fn/trait must have a stability attribute.437        if is_const438            && self.effective_visibilities.is_reachable(def_id)439            && self.tcx.lookup_const_stability(def_id).is_none()440        {441            let span = self.tcx.def_span(def_id);442            let descr = self.tcx.def_descr(def_id.to_def_id());443            self.tcx.dcx().emit_err(diagnostics::MissingConstStabAttr { span, descr });444        }445    }446}447448impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> {449    type NestedFilter = nested_filter::OnlyBodies;450451    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {452        self.tcx453    }454455    fn visit_item(&mut self, i: &'tcx Item<'tcx>) {456        self.check_compatible_stability(i.owner_id.def_id);457458        // Inherent impls and foreign modules serve only as containers for other items,459        // they don't have their own stability. They still can be annotated as unstable460        // and propagate this instability to children, but this annotation is completely461        // optional. They inherit stability from their parents when unannotated.462        if !matches!(463            i.kind,464            hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })465                | hir::ItemKind::ForeignMod { .. }466        ) {467            self.check_missing_stability(i.owner_id.def_id);468        }469470        // Ensure stable `const fn` have a const stability attribute.471        self.check_missing_const_stability(i.owner_id.def_id);472473        intravisit::walk_item(self, i)474    }475476    fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {477        self.check_compatible_stability(ti.owner_id.def_id);478        self.check_missing_stability(ti.owner_id.def_id);479        intravisit::walk_trait_item(self, ti);480    }481482    fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {483        self.check_compatible_stability(ii.owner_id.def_id);484        if let hir::ImplItemImplKind::Inherent { .. } = ii.impl_kind {485            self.check_missing_stability(ii.owner_id.def_id);486            self.check_missing_const_stability(ii.owner_id.def_id);487        }488        intravisit::walk_impl_item(self, ii);489    }490491    fn visit_variant(&mut self, var: &'tcx Variant<'tcx>) {492        self.check_compatible_stability(var.def_id);493        self.check_missing_stability(var.def_id);494        if let Some(ctor_def_id) = var.data.ctor_def_id() {495            self.check_missing_stability(ctor_def_id);496        }497        intravisit::walk_variant(self, var);498    }499500    fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {501        self.check_compatible_stability(s.def_id);502        self.check_missing_stability(s.def_id);503        intravisit::walk_field_def(self, s);504    }505506    fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {507        self.check_compatible_stability(i.owner_id.def_id);508        self.check_missing_stability(i.owner_id.def_id);509        intravisit::walk_foreign_item(self, i);510    }511512    fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {513        self.check_compatible_stability(p.def_id);514        // Note that we don't need to `check_missing_stability` for default generic parameters,515        // as we assume that any default generic parameters without attributes are automatically516        // stable (assuming they have not inherited instability from their parent).517        intravisit::walk_generic_param(self, p);518    }519}520521/// Cross-references the feature names of unstable APIs with enabled522/// features and possibly prints errors.523fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {524    tcx.hir_visit_item_likes_in_module(module_def_id, &mut Checker { tcx });525526    let is_staged_api =527        tcx.sess.opts.unstable_opts.force_unstable_if_unmarked || tcx.features().staged_api();528    if is_staged_api {529        let effective_visibilities = &tcx.effective_visibilities(());530        let mut missing = MissingStabilityAnnotations { tcx, effective_visibilities };531        if module_def_id.is_top_level_module() {532            missing.check_missing_stability(CRATE_DEF_ID);533        }534        tcx.hir_visit_item_likes_in_module(module_def_id, &mut missing);535    }536537    if module_def_id.is_top_level_module() {538        check_unused_or_stable_features(tcx)539    }540}541542pub(crate) fn provide(providers: &mut Providers) {543    *providers = Providers {544        check_mod_unstable_api_usage,545        stability_implications,546        lookup_stability,547        lookup_const_stability,548        lookup_default_body_stability,549        lookup_deprecation_entry,550        ..*providers551    };552}553554struct Checker<'tcx> {555    tcx: TyCtxt<'tcx>,556}557558impl<'tcx> Visitor<'tcx> for Checker<'tcx> {559    type NestedFilter = nested_filter::OnlyBodies;560561    /// Because stability levels are scoped lexically, we want to walk562    /// nested items in the context of the outer item, so enable563    /// deep-walking.564    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {565        self.tcx566    }567568    fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {569        match item.kind {570            hir::ItemKind::ExternCrate(_, ident) => {571                // compiler-generated `extern crate` items have a dummy span.572                // `std` is still checked for the `restricted-std` feature.573                if item.span.is_dummy() && ident.name != sym::std {574                    return;575                }576577                let Some(cnum) = self.tcx.extern_mod_stmt_cnum(item.owner_id.def_id) else {578                    return;579                };580                let def_id = cnum.as_def_id();581                self.tcx.check_stability(def_id, Some(item.hir_id()), item.span, None);582            }583584            // For implementations of traits, check the stability of each item585            // individually as it's possible to have a stable trait with unstable586            // items.587            hir::ItemKind::Impl(hir::Impl {588                of_trait: Some(of_trait),589                self_ty,590                items,591                constness,592                ..593            }) => {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, Stability{stability, span} => (*stability, *span));598599                    // FIXME(jdonszelmann): make it impossible to miss the or_else in the typesystem600                    let const_stab =601                        find_attr!(attrs, RustcConstStability{stability, ..} => *stability);602603                    let unstable_feature_stab = find_attr!(attrs, UnstableFeatureBound(i) => i)604                        .map(|i| i.as_slice())605                        .unwrap_or_default();606607                    // If this impl block has an #[unstable] attribute, give an608                    // error if all involved types and traits are stable, because609                    // it will have no effect.610                    // See: https://github.com/rust-lang/rust/issues/55436611                    //612                    // The exception is when there are both  #[unstable_feature_bound(..)] and613                    //  #![unstable(feature = "..", issue = "..")] that have the same symbol because614                    // 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                    )) = stab626                    {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);630631                        // Skip the lint if the impl is marked as unstable using632                        // #[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                        }639640                        // do not lint when the trait isn't resolved, since resolution error should641                        // be fixed first642                        if of_trait.trait_ref.path.res != Res::Err643                            && c.fully_stable644                            && !unstable_feature_bound_in_effect645                        {646                            self.tcx.emit_node_span_lint(647                                INEFFECTIVE_UNSTABLE_TRAIT_IMPL,648                                item.hir_id(),649                                span,650                                diagnostics::IneffectiveUnstableImpl,651                            );652                        }653                    }654655                    if features.const_trait_impl()656                        && let hir::Constness::Const { .. } = constness657                    {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 stable662                                // needs to have an error emitted.663                                // Note: Remove this error once `const_trait_impl` is stabilized664                                self.tcx.dcx().emit_err(diagnostics::TraitImplConstStable {665                                    span: item.span,666                                });667                                true668                            }669                            Some(_) => false,670                        };671672                        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();678679                                let impl_stability = if stable_or_implied_stable {680                                    diagnostics::ImplConstStability::Stable { span: item.span }681                                } else {682                                    diagnostics::ImplConstStability::Unstable { span: item.span }683                                };684                                let trait_stability = if const_stab.is_const_stable() {685                                    diagnostics::TraitConstStability::Stable { span: trait_span }686                                } else {687                                    diagnostics::TraitConstStability::Unstable { span: trait_span }688                                };689690                                self.tcx.dcx().emit_err(691                                    diagnostics::TraitImplConstStabilityMismatch {692                                        span: item.span,693                                        impl_stability,694                                        trait_stability,695                                    },696                                );697                            }698                        }699                    }700                }701702                if let hir::Constness::Const { .. } = constness703                    && let Some(def_id) = of_trait.trait_ref.trait_def_id()704                {705                    // FIXME(const_trait_impl): Improve the span here.706                    self.tcx.check_const_stability(707                        def_id,708                        of_trait.trait_ref.path.span,709                        of_trait.trait_ref.path.span,710                    );711                }712713                for impl_item_ref in items {714                    let impl_item = self.tcx.associated_item(impl_item_ref.owner_id);715716                    if let AssocContainer::TraitImpl(Ok(def_id)) = impl_item.container {717                        // Pass `None` to skip deprecation warnings.718                        self.tcx.check_stability(719                            def_id,720                            None,721                            self.tcx.def_span(impl_item_ref.owner_id),722                            None,723                        );724                    }725                }726            }727728            _ => (/* pass */),729        }730        intravisit::walk_item(self, item);731    }732733    fn visit_poly_trait_ref(&mut self, t: &'tcx hir::PolyTraitRef<'tcx>) {734        match t.modifiers.constness {735            hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) => {736                if let Some(def_id) = t.trait_ref.trait_def_id() {737                    self.tcx.check_const_stability(def_id, t.trait_ref.path.span, span);738                }739            }740            hir::BoundConstness::Never => {}741        }742        intravisit::walk_poly_trait_ref(self, t);743    }744745    fn visit_use(&mut self, path: &'tcx UsePath<'tcx>, hir_id: HirId) {746        let res = path.res;747748        // A use item can import something from two namespaces at the same time.749        // For deprecation/stability we don't want to warn twice.750        // This specifically happens with constructors for unit/tuple structs.751        if let Some(ty_ns_res) = res.type_ns752            && let Some(value_ns_res) = res.value_ns753            && let Some(type_ns_did) = ty_ns_res.opt_def_id()754            && let Some(value_ns_did) = value_ns_res.opt_def_id()755            && let DefKind::Ctor(.., _) = self.tcx.def_kind(value_ns_did)756            && self.tcx.parent(value_ns_did) == type_ns_did757        {758            // Only visit the value namespace path when we've detected a duplicate,759            // not the type namespace path.760            let UsePath { segments, res: _, span } = *path;761            self.visit_path(&Path { segments, res: value_ns_res, span }, hir_id);762763            // Though, visit the macro namespace if it exists,764            // regardless of the checks above relating to constructors.765            if let Some(res) = res.macro_ns {766                self.visit_path(&Path { segments, res, span }, hir_id);767            }768        } else {769            // if there's no duplicate, just walk as normal770            intravisit::walk_use(self, path, hir_id)771        }772    }773774    fn visit_path(&mut self, path: &hir::Path<'tcx>, id: hir::HirId) {775        if let Some(def_id) = path.res.opt_def_id() {776            let method_span = path.segments.last().map(|s| s.ident.span);777            let item_is_allowed = self.tcx.check_stability_allow_unstable(778                def_id,779                Some(id),780                path.span,781                method_span,782                if is_unstable_reexport(self.tcx, id) {783                    AllowUnstable::Yes784                } else {785                    AllowUnstable::No786                },787            );788789            if item_is_allowed {790                // The item itself is allowed; check whether the path there is also allowed.791                let is_allowed_through_unstable_modules: Option<Symbol> =792                    self.tcx.lookup_stability(def_id).and_then(|stab| match stab.level {793                        StabilityLevel::Stable { allowed_through_unstable_modules, .. } => {794                            allowed_through_unstable_modules795                        }796                        _ => None,797                    });798799                // Check parent modules stability as well if the item the path refers to is itself800                // stable. We only emit errors for unstable path segments if the item is stable801                // or allowed because stability is often inherited, so the most common case is that802                // both the segments and the item are unstable behind the same feature flag.803                //804                // We check here rather than in `visit_path_segment` to prevent visiting the last805                // path segment twice806                //807                // We include special cases via #[rustc_allowed_through_unstable_modules] for items808                // that were accidentally stabilized through unstable paths before this check was809                // added, such as `core::intrinsics::transmute`810                let parents = path.segments.iter().rev().skip(1);811                for path_segment in parents {812                    if let Some(def_id) = path_segment.res.opt_def_id() {813                        match is_allowed_through_unstable_modules {814                            None => {815                                // Emit a hard stability error if this path is not stable.816817                                // use `None` for id to prevent deprecation check818                                self.tcx.check_stability_allow_unstable(819                                    def_id,820                                    None,821                                    path_segment.ident.span,822                                    None,823                                    if is_unstable_reexport(self.tcx, id) {824                                        AllowUnstable::Yes825                                    } else {826                                        AllowUnstable::No827                                    },828                                );829                            }830                            Some(deprecation) => {831                                // Call the stability check directly so that we can control which832                                // diagnostic is emitted.833                                let eval_result = self.tcx.eval_stability_allow_unstable(834                                    def_id,835                                    None,836                                    path.span,837                                    None,838                                    if is_unstable_reexport(self.tcx, id) {839                                        AllowUnstable::Yes840                                    } else {841                                        AllowUnstable::No842                                    },843                                );844                                let is_allowed = matches!(eval_result, EvalResult::Allow);845                                if !is_allowed {846                                    // Calculating message for lint involves calling `self.def_path_str`,847                                    // which will by default invoke the expensive `visible_parent_map` query.848                                    // Skip all that work if the lint is allowed anyway.849                                    if self.tcx.lint_level_spec_at_node(DEPRECATED, id).is_allow() {850                                        return;851                                    }852                                    // Show a deprecation message.853                                    let def_path =854                                        with_no_trimmed_paths!(self.tcx.def_path_str(def_id));855                                    let def_kind = self.tcx.def_descr(def_id);856                                    let diag = Deprecated {857                                        sub: None,858                                        kind: def_kind.to_owned(),859                                        path: def_path,860                                        note: Some(deprecation),861                                        since_kind: lint::DeprecatedSinceKind::InEffect,862                                    };863                                    self.tcx.emit_node_span_lint(864                                        DEPRECATED,865                                        id,866                                        method_span.unwrap_or(path.span),867                                        diag,868                                    );869                                }870                            }871                        }872                    }873                }874            }875        }876877        intravisit::walk_path(self, path)878    }879}880881/// Check whether a path is a `use` item that has been marked as unstable.882///883/// See issue #94972 for details on why this is a special case884fn is_unstable_reexport(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {885    // Get the LocalDefId so we can lookup the item to check the kind.886    let Some(owner) = id.as_owner() else {887        return false;888    };889    let def_id = owner.def_id;890891    let Some(stab) = tcx.lookup_stability(def_id) else {892        return false;893    };894895    if stab.level.is_stable() {896        // The re-export is not marked as unstable, don't override897        return false;898    }899900    // If this is a path that isn't a use, we don't need to do anything special901    if !matches!(tcx.hir_expect_item(def_id).kind, ItemKind::Use(..)) {902        return false;903    }904905    true906}907908struct CheckTraitImplStable<'tcx> {909    tcx: TyCtxt<'tcx>,910    fully_stable: bool,911}912913impl<'tcx> Visitor<'tcx> for CheckTraitImplStable<'tcx> {914    fn visit_path(&mut self, path: &hir::Path<'tcx>, _id: hir::HirId) {915        if let Some(def_id) = path.res.opt_def_id()916            && let Some(stab) = self.tcx.lookup_stability(def_id)917        {918            self.fully_stable &= stab.level.is_stable();919        }920        intravisit::walk_path(self, path)921    }922923    fn visit_trait_ref(&mut self, t: &'tcx TraitRef<'tcx>) {924        if let Res::Def(DefKind::Trait, trait_did) = t.path.res {925            if let Some(stab) = self.tcx.lookup_stability(trait_did) {926                self.fully_stable &= stab.level.is_stable();927            }928        }929        intravisit::walk_trait_ref(self, t)930    }931932    fn visit_ty(&mut self, t: &'tcx Ty<'tcx, AmbigArg>) {933        if let TyKind::Never = t.kind {934            self.fully_stable = false;935        }936        if let TyKind::FnPtr(function) = t.kind {937            if extern_abi_stability(function.abi).is_err() {938                self.fully_stable = false;939            }940        }941        intravisit::walk_ty(self, t)942    }943944    fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {945        for ty in fd.inputs {946            self.visit_ty_unambig(ty)947        }948        if let hir::FnRetTy::Return(output_ty) = fd.output {949            match output_ty.kind {950                TyKind::Never => {} // `-> !` is stable951                _ => self.visit_ty_unambig(output_ty),952            }953        }954    }955}956957/// Given the list of enabled features that were not language features (i.e., that958/// were expected to be library features), and the list of features used from959/// libraries, identify activated features that don't exist and error about them.960// This is `pub` for rustdoc. rustc should call it through `check_mod_unstable_api_usage`.961pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {962    let _prof_timer = tcx.sess.timer("unused_lib_feature_checking");963964    let enabled_lang_features = tcx.features().enabled_lang_features();965    let mut lang_features = UnordSet::default();966    for EnabledLangFeature { gate_name, attr_sp, stable_since } in enabled_lang_features {967        if let Some(version) = stable_since {968            // Mark the feature as enabled, to ensure that it is not marked as unused.969            let _ = tcx.features().enabled(*gate_name);970971            // Warn if the user has enabled an already-stable lang feature.972            unnecessary_stable_feature_lint(tcx, *attr_sp, *gate_name, *version);973        }974        if !lang_features.insert(gate_name) {975            // Warn if the user enables a lang feature multiple times.976            duplicate_feature_lint(tcx, *attr_sp, *gate_name);977        }978    }979980    let enabled_lib_features = tcx.features().enabled_lib_features();981    let mut remaining_lib_features = FxIndexMap::default();982    for EnabledLibFeature { gate_name, attr_sp } in enabled_lib_features {983        if remaining_lib_features.contains_key(gate_name) {984            // Warn if the user enables a lib feature multiple times.985            duplicate_feature_lint(tcx, *attr_sp, *gate_name);986        }987        remaining_lib_features.insert(*gate_name, *attr_sp);988    }989    // `stdbuild` has special handling for `libc`, so we need to990    // recognise the feature when building std.991    // Likewise, libtest is handled specially, so `test` isn't992    // available as we'd like it to be.993    // FIXME: only remove `libc` when `stdbuild` is enabled.994    // FIXME: remove special casing for `test`.995    // FIXME(#120456) - is `swap_remove` correct?996    remaining_lib_features.swap_remove(&sym::libc);997    remaining_lib_features.swap_remove(&sym::test);998999    /// For each feature in `defined_features`..1000    ///1001    /// - If it is in `remaining_lib_features` (those features with `#![feature(..)]` attributes in1002    ///   the current crate), check if it is stable (or partially stable) and thus an unnecessary1003    ///   attribute.1004    /// - If it is in `remaining_implications` (a feature that is referenced by an `implied_by`1005    ///   from the current crate), then remove it from the remaining implications.1006    ///1007    /// Once this function has been invoked for every feature (local crate and all extern crates),1008    /// then..1009    ///1010    /// - If features remain in `remaining_lib_features`, then the user has enabled a feature that1011    ///   does not exist.1012    /// - If features remain in `remaining_implications`, the `implied_by` refers to a feature that1013    ///   does not exist.1014    ///1015    /// By structuring the code in this way: checking the features defined from each crate one at a1016    /// time, less loading from metadata is performed and thus compiler performance is improved.1017    fn check_features<'tcx>(1018        tcx: TyCtxt<'tcx>,1019        remaining_lib_features: &mut FxIndexMap<Symbol, Span>,1020        remaining_implications: &mut UnordMap<Symbol, Symbol>,1021        defined_features: &LibFeatures,1022        all_implications: &UnordMap<Symbol, Symbol>,1023    ) {1024        for (feature, stability) in defined_features.to_sorted_vec() {1025            if let FeatureStability::AcceptedSince(since) = stability1026                && let Some(span) = remaining_lib_features.get(&feature)1027            {1028                // Mark the feature as enabled, to ensure that it is not marked as unused.1029                let _ = tcx.features().enabled(feature);10301031                // Warn if the user has enabled an already-stable lib feature.1032                if let Some(implies) = all_implications.get(&feature) {1033                    unnecessary_partially_stable_feature_lint(tcx, *span, feature, *implies, since);1034                } else {1035                    unnecessary_stable_feature_lint(tcx, *span, feature, since);1036                }1037            }1038            // FIXME(#120456) - is `swap_remove` correct?1039            remaining_lib_features.swap_remove(&feature);10401041            // `feature` is the feature doing the implying, but `implied_by` is the feature with1042            // the attribute that establishes this relationship. `implied_by` is guaranteed to be a1043            // feature defined in the local crate because `remaining_implications` is only the1044            // implications from this crate.1045            remaining_implications.remove(&feature);10461047            if let FeatureStability::Unstable { old_name: Some(alias) } = stability1048                && let Some(span) = remaining_lib_features.swap_remove(&alias)1049            {1050                tcx.dcx().emit_err(diagnostics::RenamedFeature { span, feature, alias });1051            }10521053            if remaining_lib_features.is_empty() && remaining_implications.is_empty() {1054                break;1055            }1056        }1057    }10581059    // All local crate implications need to have the feature that implies it confirmed to exist.1060    let mut remaining_implications = tcx.stability_implications(LOCAL_CRATE).clone();10611062    // We always collect the lib features enabled in the current crate, even if there are1063    // no unknown features, because the collection also does feature attribute validation.1064    let local_defined_features = tcx.lib_features(LOCAL_CRATE);1065    if !remaining_lib_features.is_empty() || !remaining_implications.is_empty() {1066        let crates = tcx.crates(());10671068        // Loading the implications of all crates is unavoidable to be able to emit the partial1069        // stabilization diagnostic, but it can be avoided when there are no1070        // `remaining_lib_features`.1071        let mut all_implications = remaining_implications.clone();1072        for &cnum in crates {1073            all_implications1074                .extend_unord(tcx.stability_implications(cnum).items().map(|(k, v)| (*k, *v)));1075        }10761077        check_features(1078            tcx,1079            &mut remaining_lib_features,1080            &mut remaining_implications,1081            local_defined_features,1082            &all_implications,1083        );10841085        for &cnum in crates {1086            if remaining_lib_features.is_empty() && remaining_implications.is_empty() {1087                break;1088            }1089            check_features(1090                tcx,1091                &mut remaining_lib_features,1092                &mut remaining_implications,1093                tcx.lib_features(cnum),1094                &all_implications,1095            );1096        }10971098        if !remaining_lib_features.is_empty() {1099            let lang_features =1100                UNSTABLE_LANG_FEATURES.iter().map(|feature| feature.name).collect::<Vec<_>>();1101            let lib_features = crates1102                .iter()1103                .flat_map(|&cnum| {1104                    tcx.lib_features(cnum).stability.keys().copied().into_sorted_stable_ord()1105                })1106                .collect::<Vec<_>>();11071108            let valid_feature_names = [lang_features, lib_features].concat();11091110            // Collect all of the marked as "removed" features1111            let unstable_removed_features = crates1112                .iter()1113                .flat_map(|&cnum| {1114                    find_attr!(tcx, cnum.as_def_id(), UnstableRemoved(rem_features) => rem_features)1115                        .into_iter()1116                        .flatten()1117                })1118                .collect::<Vec<_>>();11191120            for (feature, span) in remaining_lib_features {1121                if let Some(removed) =1122                    unstable_removed_features.iter().find(|removed| removed.feature == feature)1123                {1124                    tcx.dcx().emit_err(diagnostics::FeatureRemoved {1125                        span,1126                        feature,1127                        reason: removed.reason,1128                        link: removed.link,1129                        since: removed.since.to_string(),1130                    });1131                } else {1132                    let suggestion =1133                        feature.find_similar(&valid_feature_names).map(|(actual_name, _)| {1134                            diagnostics::MisspelledFeature { span, actual_name }1135                        });1136                    tcx.dcx().emit_err(diagnostics::UnknownFeature { span, feature, suggestion });1137                }1138            }1139        }1140    }11411142    for (&implied_by, &feature) in remaining_implications.to_sorted_stable_ord() {1143        let local_defined_features = tcx.lib_features(LOCAL_CRATE);1144        let span = local_defined_features1145            .stability1146            .get(&feature)1147            .expect("feature that implied another does not exist")1148            .1;1149        tcx.dcx().emit_err(diagnostics::ImpliedFeatureNotExist { span, feature, implied_by });1150    }11511152    // FIXME(#44232): the `used_features` table no longer exists, so we1153    // don't lint about unused features. We should re-enable this one day!1154}11551156fn unnecessary_partially_stable_feature_lint(1157    tcx: TyCtxt<'_>,1158    span: Span,1159    feature: Symbol,1160    implies: Symbol,1161    since: Symbol,1162) {1163    tcx.emit_node_span_lint(1164        lint::builtin::STABLE_FEATURES,1165        hir::CRATE_HIR_ID,1166        span,1167        diagnostics::UnnecessaryPartialStableFeature {1168            span,1169            line: tcx.sess.source_map().span_extend_to_line(span),1170            feature,1171            since,1172            implies,1173        },1174    );1175}11761177fn unnecessary_stable_feature_lint(1178    tcx: TyCtxt<'_>,1179    span: Span,1180    feature: Symbol,1181    mut since: Symbol,1182) {1183    if since.as_str() == VERSION_PLACEHOLDER {1184        since = sym::env_CFG_RELEASE;1185    }1186    tcx.emit_node_span_lint(1187        lint::builtin::STABLE_FEATURES,1188        hir::CRATE_HIR_ID,1189        span,1190        diagnostics::UnnecessaryStableFeature { feature, since },1191    );1192}11931194fn duplicate_feature_lint(tcx: TyCtxt<'_>, span: Span, feature: Symbol) {1195    tcx.emit_node_span_lint(1196        lint::builtin::DUPLICATE_FEATURES,1197        hir::CRATE_HIR_ID,1198        span,1199        diagnostics::DuplicateFeature { feature },1200    );1201}

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.