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, LocalModId};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_lint_defs as lint;20use rustc_lint_defs::builtin::{21 DEPRECATED, DUPLICATE_FEATURES, INEFFECTIVE_UNSTABLE_TRAIT_IMPL, STABLE_FEATURES,22};23use rustc_middle::hir::nested_filter;24use rustc_middle::middle::lib_features::{FeatureStability, LibFeatures};25use rustc_middle::middle::privacy::EffectiveVisibilities;26use rustc_middle::middle::stability::{AllowUnstable, Deprecated, DeprecationEntry, EvalResult};27use rustc_middle::query::{LocalCrate, Providers};28use rustc_middle::ty::print::with_no_trimmed_paths;29use rustc_middle::ty::{AssocContainer, TyCtxt};30use rustc_span::{Span, Symbol, sym};31use tracing::instrument;3233use crate::diagnostics;3435#[derive(PartialEq)]36enum AnnotationKind {37 /// Annotation is required if not inherited from unstable parents.38 Required,39 /// Annotation is useless, reject it.40 Prohibited,41 /// Deprecation annotation is useless, reject it. (Stability attribute is still required.)42 DeprecationProhibited,43 /// Annotation itself is useless, but it can be propagated to children.44 Container,45}4647fn inherit_deprecation(def_kind: DefKind) -> bool {48 match def_kind {49 DefKind::LifetimeParam | DefKind::TyParam | DefKind::ConstParam => false,50 _ => true,51 }52}5354fn inherit_const_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {55 let def_kind = tcx.def_kind(def_id);56 match def_kind {57 DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst { .. } => {58 match tcx.def_kind(tcx.local_parent(def_id)) {59 DefKind::Trait | DefKind::Impl { .. } => true,60 _ => false,61 }62 }63 DefKind::Closure => true,64 _ => false,65 }66}6768fn annotation_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> AnnotationKind {69 let def_kind = tcx.def_kind(def_id);70 match def_kind {71 // Inherent impls and foreign modules serve only as containers for other items,72 // they don't have their own stability. They still can be annotated as unstable73 // and propagate this unstability to children, but this annotation is completely74 // optional. They inherit stability from their parents when unannotated.75 DefKind::Impl { of_trait: false } | DefKind::ForeignMod => AnnotationKind::Container,76 DefKind::Impl { of_trait: true } => AnnotationKind::DeprecationProhibited,7778 // Allow stability attributes on default generic arguments.79 DefKind::TyParam | DefKind::ConstParam => {80 match &tcx.hir_node_by_def_id(def_id).expect_generic_param().kind {81 hir::GenericParamKind::Type { default: Some(_), .. }82 | hir::GenericParamKind::Const { default: Some(_), .. } => {83 AnnotationKind::Container84 }85 _ => AnnotationKind::Prohibited,86 }87 }8889 // Impl items in trait impls cannot have stability.90 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst { .. } => {91 match tcx.def_kind(tcx.local_parent(def_id)) {92 DefKind::Impl { of_trait: true } => AnnotationKind::Prohibited,93 _ => AnnotationKind::Required,94 }95 }9697 _ => AnnotationKind::Required,98 }99}100101fn lookup_deprecation_entry(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<DeprecationEntry> {102 let depr = find_attr!(tcx, def_id,103 Deprecated { deprecation, span: _ } => *deprecation104 );105106 let Some(depr) = depr else {107 if inherit_deprecation(tcx.def_kind(def_id)) {108 let parent_id = tcx.opt_local_parent(def_id)?;109 let parent_depr = tcx.lookup_deprecation_entry(parent_id)?;110 return Some(parent_depr);111 }112113 return None;114 };115116 // `Deprecation` is just two pointers, no need to intern it117 Some(DeprecationEntry::local(depr, def_id))118}119120fn inherit_stability(def_kind: DefKind) -> bool {121 match def_kind {122 DefKind::Field | DefKind::Variant | DefKind::Ctor(..) => true,123 _ => false,124 }125}126127/// If the `-Z force-unstable-if-unmarked` flag is passed then we provide128/// a parent stability annotation which indicates that this is private129/// with the `rustc_private` feature. This is intended for use when130/// compiling library and `rustc_*` crates themselves so we can leverage crates.io131/// while maintaining the invariant that all sysroot crates are unstable132/// by default and are unable to be used.133const FORCE_UNSTABLE: Stability = Stability {134 level: StabilityLevel::Unstable {135 reason: UnstableReason::Default,136 issue: NonZero::new(27812),137 implied_by: None,138 old_name: None,139 },140 feature: sym::rustc_private,141};142143#[instrument(level = "debug", skip(tcx))]144fn lookup_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<Stability> {145 // Propagate unstability. This can happen even for non-staged-api crates in case146 // -Zforce-unstable-if-unmarked is set.147 if !tcx.features().staged_api() {148 if !tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {149 return None;150 }151152 let Some(parent) = tcx.opt_local_parent(def_id) else { return Some(FORCE_UNSTABLE) };153154 if inherit_deprecation(tcx.def_kind(def_id)) {155 let parent = tcx.lookup_stability(parent)?;156 if parent.is_unstable() {157 return Some(parent);158 }159 }160161 return None;162 }163164 // # Regular stability165 let stab = find_attr!(tcx, def_id, Stability { stability, span: _ } => *stability);166167 if let Some(stab) = stab {168 return Some(stab);169 }170171 if inherit_deprecation(tcx.def_kind(def_id)) {172 let Some(parent) = tcx.opt_local_parent(def_id) else {173 return tcx174 .sess175 .opts176 .unstable_opts177 .force_unstable_if_unmarked178 .then_some(FORCE_UNSTABLE);179 };180 let parent = tcx.lookup_stability(parent)?;181 if parent.is_unstable() || inherit_stability(tcx.def_kind(def_id)) {182 return Some(parent);183 }184 }185186 None187}188189#[instrument(level = "debug", skip(tcx))]190fn lookup_default_body_stability(191 tcx: TyCtxt<'_>,192 def_id: LocalDefId,193) -> Option<DefaultBodyStability> {194 if !tcx.features().staged_api() {195 return None;196 }197198 // FIXME: check that this item can have body stability199 find_attr!(tcx, def_id, RustcBodyStability { stability, .. } => *stability)200}201202#[instrument(level = "debug", skip(tcx))]203fn lookup_const_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ConstStability> {204 if !tcx.features().staged_api() {205 // Propagate unstability. This can happen even for non-staged-api crates in case206 // -Zforce-unstable-if-unmarked is set.207 if inherit_deprecation(tcx.def_kind(def_id)) {208 let parent = tcx.opt_local_parent(def_id)?;209 let parent_stab = tcx.lookup_stability(parent)?;210 if parent_stab.is_unstable()211 && let Some(fn_sig) = tcx.hir_node_by_def_id(def_id).fn_sig()212 && matches!(fn_sig.header.constness, Constness::Const { .. })213 {214 let const_stable_indirect = find_attr!(tcx, def_id, RustcConstStableIndirect);215 return Some(ConstStability::unmarked(const_stable_indirect, parent_stab));216 }217 }218219 return None;220 }221222 let const_stable_indirect = find_attr!(tcx, def_id, RustcConstStableIndirect);223 let const_stab =224 find_attr!(tcx, def_id, RustcConstStability { stability, span: _ } => *stability);225226 // After checking the immediate attributes, get rid of the span and compute implied227 // const stability: inherit feature gate from regular stability.228 let mut const_stab = const_stab229 .map(|const_stab| ConstStability::from_partial(const_stab, const_stable_indirect));230231 // If this is a const fn but not annotated with stability markers, see if we can inherit232 // regular stability.233 if let Some(fn_sig) = tcx.hir_node_by_def_id(def_id).fn_sig()234 && matches!(fn_sig.header.constness, Constness::Const { .. })235 && const_stab.is_none()236 // We only ever inherit unstable features.237 && let Some(inherit_regular_stab) = tcx.lookup_stability(def_id)238 && inherit_regular_stab.is_unstable()239 {240 const_stab = Some(ConstStability {241 // We subject these implicitly-const functions to recursive const stability.242 const_stable_indirect: true,243 promotable: false,244 level: inherit_regular_stab.level,245 feature: inherit_regular_stab.feature,246 });247 }248249 if let Some(const_stab) = const_stab {250 return Some(const_stab);251 }252253 // `impl const Trait for Type` items forward their const stability to their immediate children.254 // FIXME(const_trait_impl): how is this supposed to interact with `#[rustc_const_stable_indirect]`?255 // Currently, once that is set, we do not inherit anything from the parent any more.256 if inherit_const_stability(tcx, def_id) {257 let parent = tcx.opt_local_parent(def_id)?;258 let parent = tcx.lookup_const_stability(parent)?;259 if parent.is_const_unstable() {260 return Some(parent);261 }262 }263264 None265}266267fn stability_implications(tcx: TyCtxt<'_>, LocalCrate: LocalCrate) -> UnordMap<Symbol, Symbol> {268 let mut implications = UnordMap::default();269270 let mut register_implication = |def_id| {271 if let Some(stability) = tcx.lookup_stability(def_id)272 && let StabilityLevel::Unstable { implied_by: Some(implied_by), .. } = stability.level273 {274 implications.insert(implied_by, stability.feature);275 }276277 if let Some(stability) = tcx.lookup_const_stability(def_id)278 && let StabilityLevel::Unstable { implied_by: Some(implied_by), .. } = stability.level279 {280 implications.insert(implied_by, stability.feature);281 }282 };283284 if tcx.features().staged_api() {285 register_implication(CRATE_DEF_ID);286 for def_id in tcx.hir_crate_items(()).definitions() {287 register_implication(def_id);288 let def_kind = tcx.def_kind(def_id);289 if def_kind.is_adt() {290 let adt = tcx.adt_def(def_id);291 for variant in adt.variants() {292 if variant.def_id != def_id.to_def_id() {293 register_implication(variant.def_id.expect_local());294 }295 for field in &variant.fields {296 register_implication(field.did.expect_local());297 }298 if let Some(ctor_def_id) = variant.ctor_def_id() {299 register_implication(ctor_def_id.expect_local())300 }301 }302 }303 if def_kind.has_generics() {304 for param in tcx.generics_of(def_id).own_params.iter() {305 register_implication(param.def_id.expect_local())306 }307 }308 }309 }310311 implications312}313314struct MissingStabilityAnnotations<'tcx> {315 tcx: TyCtxt<'tcx>,316 effective_visibilities: &'tcx EffectiveVisibilities,317}318319impl<'tcx> MissingStabilityAnnotations<'tcx> {320 /// Verify that deprecation and stability attributes make sense with one another.321 #[instrument(level = "trace", skip(self))]322 fn check_compatible_stability(&self, def_id: LocalDefId) {323 if !self.tcx.features().staged_api() {324 return;325 }326327 let depr = self.tcx.lookup_deprecation_entry(def_id);328 let stab = self.tcx.lookup_stability(def_id);329 let const_stab = self.tcx.lookup_const_stability(def_id);330331 macro_rules! find_attr_span {332 ($name:ident) => {{333 let attrs = self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id));334 find_attr!(attrs, AttributeKind::$name { span, .. } => *span)335 }}336 }337338 if stab.is_none()339 && depr.map_or(false, |d| d.attr.is_since_rustc_version())340 && let Some(span) = find_attr_span!(Deprecated)341 {342 self.tcx.dcx().emit_err(diagnostics::DeprecatedAttribute { span });343 }344345 if let Some(stab) = stab {346 // Error if prohibited, or can't inherit anything from a container.347 let kind = annotation_kind(self.tcx, def_id);348 if kind == AnnotationKind::Prohibited349 || (kind == AnnotationKind::Container && stab.level.is_stable() && depr.is_some())350 {351 if let Some(span) = find_attr_span!(Stability) {352 let item_sp = self.tcx.def_span(def_id);353 self.tcx.dcx().emit_err(diagnostics::UselessStability { span, item_sp });354 }355 }356357 // Check if deprecated_since < stable_since. If it is,358 // this is *almost surely* an accident.359 if let Some(depr) = depr360 && let DeprecatedSince::RustcVersion(dep_since) = depr.attr.since361 && let StabilityLevel::Stable { since: stab_since, .. } = stab.level362 && let Some(span) = find_attr_span!(Stability)363 {364 let item_sp = self.tcx.def_span(def_id);365 match stab_since {366 StableSince::Current => {367 self.tcx368 .dcx()369 .emit_err(diagnostics::CannotStabilizeDeprecated { span, item_sp });370 }371 StableSince::Version(stab_since) => {372 if dep_since < stab_since {373 self.tcx374 .dcx()375 .emit_err(diagnostics::CannotStabilizeDeprecated { span, item_sp });376 }377 }378 StableSince::Err(_) => {379 // An error already reported. Assume the unparseable stabilization380 // version is older than the deprecation version.381 }382 }383 }384 }385386 // If the current node is a function with const stability attributes (directly given or387 // implied), check if the function/method is const or the parent impl block is const.388 let fn_sig = self.tcx.hir_node_by_def_id(def_id).fn_sig();389 if let Some(fn_sig) = fn_sig390 && !matches!(fn_sig.header.constness, Constness::Const { .. })391 && const_stab.is_some()392 && find_attr_span!(RustcConstStability).is_some()393 {394 self.tcx.dcx().emit_err(diagnostics::MissingConstErr { fn_sig_span: fn_sig.span });395 }396397 // If this is marked const *stable*, it must also be regular-stable.398 if let Some(const_stab) = const_stab399 && let Some(fn_sig) = fn_sig400 && const_stab.is_const_stable()401 && !stab.is_some_and(|s| s.is_stable())402 && let Some(path_span) = find_attr_span!(RustcConstStability)403 {404 self.tcx.dcx().emit_err(diagnostics::ConstStableNotStable {405 fn_sig_span: fn_sig.span,406 path_span,407 });408 }409410 if let Some(stab) = &const_stab411 && stab.is_const_stable()412 && stab.const_stable_indirect413 && let Some(span) = find_attr_span!(RustcConstStability)414 {415 self.tcx.dcx().emit_err(diagnostics::RustcConstStableIndirectPairing { span });416 }417 }418419 #[instrument(level = "debug", skip(self))]420 fn check_missing_stability(&self, def_id: LocalDefId) {421 let stab = self.tcx.lookup_stability(def_id);422 self.tcx.ensure_ok().lookup_const_stability(def_id);423 if !self.tcx.sess.is_test_crate()424 && stab.is_none()425 && self.effective_visibilities.is_reachable(def_id)426 {427 let descr = self.tcx.def_descr(def_id.to_def_id());428 let span = self.tcx.def_span(def_id);429 self.tcx.dcx().emit_err(diagnostics::MissingStabilityAttr { span, descr });430 }431 }432433 fn check_missing_const_stability(&self, def_id: LocalDefId) {434 let is_const = self.tcx.is_const_fn(def_id.to_def_id())435 || (self.tcx.def_kind(def_id.to_def_id()) == DefKind::Trait436 && self.tcx.is_const_trait(def_id.to_def_id()));437438 // Reachable const fn/trait must have a stability attribute.439 if is_const440 && self.effective_visibilities.is_reachable(def_id)441 && self.tcx.lookup_const_stability(def_id).is_none()442 {443 let span = self.tcx.def_span(def_id);444 let descr = self.tcx.def_descr(def_id.to_def_id());445 self.tcx.dcx().emit_err(diagnostics::MissingConstStabAttr { span, descr });446 }447 }448}449450impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> {451 type NestedFilter = nested_filter::OnlyBodies;452453 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {454 self.tcx455 }456457 fn visit_item(&mut self, i: &'tcx Item<'tcx>) {458 self.check_compatible_stability(i.owner_id.def_id);459460 // Inherent impls and foreign modules serve only as containers for other items,461 // they don't have their own stability. They still can be annotated as unstable462 // and propagate this instability to children, but this annotation is completely463 // optional. They inherit stability from their parents when unannotated.464 if !matches!(465 i.kind,466 hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })467 | hir::ItemKind::ForeignMod { .. }468 ) {469 self.check_missing_stability(i.owner_id.def_id);470 }471472 // Ensure stable `const fn` have a const stability attribute.473 self.check_missing_const_stability(i.owner_id.def_id);474475 intravisit::walk_item(self, i)476 }477478 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {479 self.check_compatible_stability(ti.owner_id.def_id);480 self.check_missing_stability(ti.owner_id.def_id);481 intravisit::walk_trait_item(self, ti);482 }483484 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {485 self.check_compatible_stability(ii.owner_id.def_id);486 if let hir::ImplItemImplKind::Inherent { .. } = ii.impl_kind {487 self.check_missing_stability(ii.owner_id.def_id);488 self.check_missing_const_stability(ii.owner_id.def_id);489 }490 intravisit::walk_impl_item(self, ii);491 }492493 fn visit_variant(&mut self, var: &'tcx Variant<'tcx>) {494 self.check_compatible_stability(var.def_id);495 self.check_missing_stability(var.def_id);496 if let Some(ctor_def_id) = var.data.ctor_def_id() {497 self.check_missing_stability(ctor_def_id);498 }499 intravisit::walk_variant(self, var);500 }501502 fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {503 self.check_compatible_stability(s.def_id);504 self.check_missing_stability(s.def_id);505 intravisit::walk_field_def(self, s);506 }507508 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {509 self.check_compatible_stability(i.owner_id.def_id);510 self.check_missing_stability(i.owner_id.def_id);511 intravisit::walk_foreign_item(self, i);512 }513514 fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {515 self.check_compatible_stability(p.def_id);516 // Note that we don't need to `check_missing_stability` for default generic parameters,517 // as we assume that any default generic parameters without attributes are automatically518 // stable (assuming they have not inherited instability from their parent).519 intravisit::walk_generic_param(self, p);520 }521}522523/// Cross-references the feature names of unstable APIs with enabled524/// features and possibly prints errors.525fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, mod_id: LocalModId) {526 tcx.hir_visit_item_likes_in_module(mod_id, &mut Checker { tcx });527528 let is_staged_api =529 tcx.sess.opts.unstable_opts.force_unstable_if_unmarked || tcx.features().staged_api();530 if is_staged_api {531 let effective_visibilities = &tcx.effective_visibilities(());532 let mut missing = MissingStabilityAnnotations { tcx, effective_visibilities };533 if mod_id.is_top_level_module() {534 missing.check_missing_stability(CRATE_DEF_ID);535 }536 tcx.hir_visit_item_likes_in_module(mod_id, &mut missing);537 }538539 if mod_id.is_top_level_module() {540 check_unused_or_stable_features(tcx)541 }542}543544pub(crate) fn provide(providers: &mut Providers) {545 *providers = Providers {546 check_mod_unstable_api_usage,547 stability_implications,548 lookup_stability,549 lookup_const_stability,550 lookup_default_body_stability,551 lookup_deprecation_entry,552 ..*providers553 };554}555556struct Checker<'tcx> {557 tcx: TyCtxt<'tcx>,558}559560impl<'tcx> Visitor<'tcx> for Checker<'tcx> {561 type NestedFilter = nested_filter::OnlyBodies;562563 /// Because stability levels are scoped lexically, we want to walk564 /// nested items in the context of the outer item, so enable565 /// deep-walking.566 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {567 self.tcx568 }569570 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {571 match item.kind {572 hir::ItemKind::ExternCrate(_, ident) => {573 // compiler-generated `extern crate` items have a dummy span.574 // `std` is still checked for the `restricted-std` feature.575 if item.span.is_dummy() && ident.name != sym::std {576 return;577 }578579 let Some(cnum) = self.tcx.extern_mod_stmt_cnum(item.owner_id.def_id) else {580 return;581 };582 let def_id = cnum.as_def_id();583 self.tcx.check_stability(def_id, Some(item.hir_id()), item.span, None);584 }585586 // For implementations of traits, check the stability of each item587 // individually as it's possible to have a stable trait with unstable588 // items.589 hir::ItemKind::Impl(hir::Impl {590 of_trait: Some(of_trait),591 self_ty,592 items,593 constness,594 ..595 }) => {596 let features = self.tcx.features();597 if features.staged_api() {598 let attrs = self.tcx.hir_attrs(item.hir_id());599 let stab = find_attr!(attrs, Stability{stability, span} => (*stability, *span));600601 // FIXME(jdonszelmann): make it impossible to miss the or_else in the typesystem602 let const_stab =603 find_attr!(attrs, RustcConstStability{stability, ..} => *stability);604605 let unstable_feature_stab = find_attr!(attrs, UnstableFeatureBound(i) => i)606 .map(|i| i.as_slice())607 .unwrap_or_default();608609 // If this impl block has an #[unstable] attribute, give an610 // error if all involved types and traits are stable, because611 // it will have no effect.612 // See: https://github.com/rust-lang/rust/issues/55436613 //614 // The exception is when there are both #[unstable_feature_bound(..)] and615 // #![unstable(feature = "..", issue = "..")] that have the same symbol because616 // that can effectively mark an impl as unstable.617 //618 // For example:619 // ```620 // #[unstable_feature_bound(feat_foo)]621 // #[unstable(feature = "feat_foo", issue = "none")]622 // impl Foo for Bar {}623 // ```624 if let Some((625 Stability { level: StabilityLevel::Unstable { .. }, feature },626 span,627 )) = stab628 {629 let mut c = CheckTraitImplStable { tcx: self.tcx, fully_stable: true };630 c.visit_ty_unambig(self_ty);631 c.visit_trait_ref(&of_trait.trait_ref);632633 // Skip the lint if the impl is marked as unstable using634 // #[unstable_feature_bound(..)]635 let mut unstable_feature_bound_in_effect = false;636 for (unstable_bound_feat_name, _) in unstable_feature_stab {637 if *unstable_bound_feat_name == feature {638 unstable_feature_bound_in_effect = true;639 }640 }641642 // do not lint when the trait isn't resolved, since resolution error should643 // be fixed first644 if of_trait.trait_ref.path.res != Res::Err645 && c.fully_stable646 && !unstable_feature_bound_in_effect647 {648 self.tcx.emit_node_span_lint(649 INEFFECTIVE_UNSTABLE_TRAIT_IMPL,650 item.hir_id(),651 span,652 diagnostics::IneffectiveUnstableImpl,653 );654 }655 }656657 if features.const_trait_impl()658 && let hir::Constness::Const { .. } = constness659 {660 let stable_or_implied_stable = match const_stab {661 None => true,662 Some(stab) if stab.is_const_stable() => {663 // `#![feature(const_trait_impl)]` is unstable, so any impl declared stable664 // needs to have an error emitted.665 // Note: Remove this error once `const_trait_impl` is stabilized666 self.tcx.dcx().emit_err(diagnostics::TraitImplConstStable {667 span: item.span,668 });669 true670 }671 Some(_) => false,672 };673674 if let Some(trait_id) = of_trait.trait_ref.trait_def_id()675 && let Some(const_stab) = self.tcx.lookup_const_stability(trait_id)676 {677 // the const stability of a trait impl must match the const stability on the trait.678 if const_stab.is_const_stable() != stable_or_implied_stable {679 let trait_span = self.tcx.def_ident_span(trait_id).unwrap();680681 let impl_stability = if stable_or_implied_stable {682 diagnostics::ImplConstStability::Stable { span: item.span }683 } else {684 diagnostics::ImplConstStability::Unstable { span: item.span }685 };686 let trait_stability = if const_stab.is_const_stable() {687 diagnostics::TraitConstStability::Stable { span: trait_span }688 } else {689 diagnostics::TraitConstStability::Unstable { span: trait_span }690 };691692 self.tcx.dcx().emit_err(693 diagnostics::TraitImplConstStabilityMismatch {694 span: item.span,695 impl_stability,696 trait_stability,697 },698 );699 }700 }701 }702 }703704 if let hir::Constness::Const { .. } = constness705 && let Some(def_id) = of_trait.trait_ref.trait_def_id()706 {707 // FIXME(const_trait_impl): Improve the span here.708 self.tcx.check_const_stability(709 def_id,710 of_trait.trait_ref.path.span,711 of_trait.trait_ref.path.span,712 );713 }714715 for impl_item_ref in items {716 let impl_item = self.tcx.associated_item(impl_item_ref.owner_id);717718 if let AssocContainer::TraitImpl(Ok(def_id)) = impl_item.container {719 // Pass `None` to skip deprecation warnings.720 self.tcx.check_stability(721 def_id,722 None,723 self.tcx.def_span(impl_item_ref.owner_id),724 None,725 );726 }727 }728 }729730 _ => (/* pass */),731 }732 intravisit::walk_item(self, item);733 }734735 fn visit_poly_trait_ref(&mut self, t: &'tcx hir::PolyTraitRef<'tcx>) {736 match t.modifiers.constness {737 hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) => {738 if let Some(def_id) = t.trait_ref.trait_def_id() {739 self.tcx.check_const_stability(def_id, t.trait_ref.path.span, span);740 }741 }742 hir::BoundConstness::Never => {}743 }744 intravisit::walk_poly_trait_ref(self, t);745 }746747 fn visit_use(&mut self, path: &'tcx UsePath<'tcx>, hir_id: HirId) {748 let res = path.res;749750 // A use item can import something from two namespaces at the same time.751 // For deprecation/stability we don't want to warn twice.752 // This specifically happens with constructors for unit/tuple structs.753 if let Some(ty_ns_res) = res.type_ns754 && let Some(value_ns_res) = res.value_ns755 && let Some(type_ns_did) = ty_ns_res.opt_def_id()756 && let Some(value_ns_did) = value_ns_res.opt_def_id()757 && let DefKind::Ctor(.., _) = self.tcx.def_kind(value_ns_did)758 && self.tcx.parent(value_ns_did) == type_ns_did759 {760 // Only visit the value namespace path when we've detected a duplicate,761 // not the type namespace path.762 let UsePath { segments, res: _, span } = *path;763 self.visit_path(&Path { segments, res: value_ns_res, span }, hir_id);764765 // Though, visit the macro namespace if it exists,766 // regardless of the checks above relating to constructors.767 if let Some(res) = res.macro_ns {768 self.visit_path(&Path { segments, res, span }, hir_id);769 }770 } else {771 // if there's no duplicate, just walk as normal772 intravisit::walk_use(self, path, hir_id)773 }774 }775776 fn visit_path(&mut self, path: &hir::Path<'tcx>, id: hir::HirId) {777 if let Some(def_id) = path.res.opt_def_id() {778 let method_span = path.segments.last().map(|s| s.ident.span);779 let item_is_allowed = self.tcx.check_stability_allow_unstable(780 def_id,781 Some(id),782 path.span,783 method_span,784 if is_unstable_reexport(self.tcx, id) {785 AllowUnstable::Yes786 } else {787 AllowUnstable::No788 },789 );790791 if item_is_allowed {792 // The item itself is allowed; check whether the path there is also allowed.793 let is_allowed_through_unstable_modules: Option<Symbol> =794 self.tcx.lookup_stability(def_id).and_then(|stab| match stab.level {795 StabilityLevel::Stable { allowed_through_unstable_modules, .. } => {796 allowed_through_unstable_modules797 }798 _ => None,799 });800801 // Check parent modules stability as well if the item the path refers to is itself802 // stable. We only emit errors for unstable path segments if the item is stable803 // or allowed because stability is often inherited, so the most common case is that804 // both the segments and the item are unstable behind the same feature flag.805 //806 // We check here rather than in `visit_path_segment` to prevent visiting the last807 // path segment twice808 //809 // We include special cases via #[rustc_allowed_through_unstable_modules] for items810 // that were accidentally stabilized through unstable paths before this check was811 // added, such as `core::intrinsics::transmute`812 let parents = path.segments.iter().rev().skip(1);813 for path_segment in parents {814 if let Some(def_id) = path_segment.res.opt_def_id() {815 match is_allowed_through_unstable_modules {816 None => {817 // Emit a hard stability error if this path is not stable.818819 // use `None` for id to prevent deprecation check820 self.tcx.check_stability_allow_unstable(821 def_id,822 None,823 path_segment.ident.span,824 None,825 if is_unstable_reexport(self.tcx, id) {826 AllowUnstable::Yes827 } else {828 AllowUnstable::No829 },830 );831 }832 Some(deprecation) => {833 // Call the stability check directly so that we can control which834 // diagnostic is emitted.835 let eval_result = self.tcx.eval_stability_allow_unstable(836 def_id,837 None,838 path.span,839 None,840 if is_unstable_reexport(self.tcx, id) {841 AllowUnstable::Yes842 } else {843 AllowUnstable::No844 },845 );846 let is_allowed = matches!(eval_result, EvalResult::Allow);847 if !is_allowed {848 // Calculating message for lint involves calling `self.def_path_str`,849 // which will by default invoke the expensive `visible_parent_map` query.850 // Skip all that work if the lint is allowed anyway.851 if self.tcx.lint_level_spec_at_node(DEPRECATED, id).is_allow() {852 return;853 }854 // Show a deprecation message.855 let def_path =856 with_no_trimmed_paths!(self.tcx.def_path_str(def_id));857 let def_kind = self.tcx.def_descr(def_id);858 let diag = Deprecated {859 sub: None,860 kind: def_kind.to_owned(),861 path: def_path,862 note: Some(deprecation),863 since_kind: lint::DeprecatedSinceKind::InEffect,864 };865 self.tcx.emit_node_span_lint(866 DEPRECATED,867 id,868 method_span.unwrap_or(path.span),869 diag,870 );871 }872 }873 }874 }875 }876 }877 }878879 intravisit::walk_path(self, path)880 }881}882883/// Check whether a path is a `use` item that has been marked as unstable.884///885/// See issue #94972 for details on why this is a special case886fn is_unstable_reexport(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {887 // Get the LocalDefId so we can lookup the item to check the kind.888 let Some(owner) = id.as_owner() else {889 return false;890 };891 let def_id = owner.def_id;892893 let Some(stab) = tcx.lookup_stability(def_id) else {894 return false;895 };896897 if stab.level.is_stable() {898 // The re-export is not marked as unstable, don't override899 return false;900 }901902 // If this is a path that isn't a use, we don't need to do anything special903 if !matches!(tcx.hir_expect_item(def_id).kind, ItemKind::Use(..)) {904 return false;905 }906907 true908}909910struct CheckTraitImplStable<'tcx> {911 tcx: TyCtxt<'tcx>,912 fully_stable: bool,913}914915impl<'tcx> Visitor<'tcx> for CheckTraitImplStable<'tcx> {916 fn visit_path(&mut self, path: &hir::Path<'tcx>, _id: hir::HirId) {917 if let Some(def_id) = path.res.opt_def_id()918 && let Some(stab) = self.tcx.lookup_stability(def_id)919 {920 self.fully_stable &= stab.level.is_stable();921 }922 intravisit::walk_path(self, path)923 }924925 fn visit_trait_ref(&mut self, t: &'tcx TraitRef<'tcx>) {926 if let Res::Def(DefKind::Trait, trait_did) = t.path.res {927 if let Some(stab) = self.tcx.lookup_stability(trait_did) {928 self.fully_stable &= stab.level.is_stable();929 }930 }931 intravisit::walk_trait_ref(self, t)932 }933934 fn visit_ty(&mut self, t: &'tcx Ty<'tcx, AmbigArg>) {935 if let TyKind::Never = t.kind {936 self.fully_stable = false;937 }938 if let TyKind::FnPtr(function) = t.kind {939 if extern_abi_stability(function.abi).is_err() {940 self.fully_stable = false;941 }942 }943 intravisit::walk_ty(self, t)944 }945946 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {947 for ty in fd.inputs {948 self.visit_ty_unambig(ty)949 }950 if let hir::FnRetTy::Return(output_ty) = fd.output {951 match output_ty.kind {952 TyKind::Never => {} // `-> !` is stable953 _ => self.visit_ty_unambig(output_ty),954 }955 }956 }957}958959/// Given the list of enabled features that were not language features (i.e., that960/// were expected to be library features), and the list of features used from961/// libraries, identify activated features that don't exist and error about them.962// This is `pub` for rustdoc. rustc should call it through `check_mod_unstable_api_usage`.963pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {964 let _prof_timer = tcx.sess.timer("unused_lib_feature_checking");965966 let enabled_lang_features = tcx.features().enabled_lang_features();967 let mut lang_features = UnordSet::default();968 for EnabledLangFeature { gate_name, attr_sp, stable_since } in enabled_lang_features {969 if let Some(version) = stable_since {970 // Mark the feature as enabled, to ensure that it is not marked as unused.971 let _ = tcx.features().enabled(*gate_name);972973 // Warn if the user has enabled an already-stable lang feature.974 unnecessary_stable_feature_lint(tcx, *attr_sp, *gate_name, *version);975 }976 if !lang_features.insert(gate_name) {977 // Warn if the user enables a lang feature multiple times.978 duplicate_feature_lint(tcx, *attr_sp, *gate_name);979 }980 }981982 let enabled_lib_features = tcx.features().enabled_lib_features();983 let mut remaining_lib_features = FxIndexMap::default();984 for EnabledLibFeature { gate_name, attr_sp } in enabled_lib_features {985 if remaining_lib_features.contains_key(gate_name) {986 // Warn if the user enables a lib feature multiple times.987 duplicate_feature_lint(tcx, *attr_sp, *gate_name);988 }989 remaining_lib_features.insert(*gate_name, *attr_sp);990 }991 // `stdbuild` has special handling for `libc`, so we need to992 // recognise the feature when building std.993 // Likewise, libtest is handled specially, so `test` isn't994 // available as we'd like it to be.995 // FIXME: only remove `libc` when `stdbuild` is enabled.996 // FIXME: remove special casing for `test`.997 // FIXME(#120456) - is `swap_remove` correct?998 remaining_lib_features.swap_remove(&sym::libc);999 remaining_lib_features.swap_remove(&sym::test);10001001 /// For each feature in `defined_features`..1002 ///1003 /// - If it is in `remaining_lib_features` (those features with `#![feature(..)]` attributes in1004 /// the current crate), check if it is stable (or partially stable) and thus an unnecessary1005 /// attribute.1006 /// - If it is in `remaining_implications` (a feature that is referenced by an `implied_by`1007 /// from the current crate), then remove it from the remaining implications.1008 ///1009 /// Once this function has been invoked for every feature (local crate and all extern crates),1010 /// then..1011 ///1012 /// - If features remain in `remaining_lib_features`, then the user has enabled a feature that1013 /// does not exist.1014 /// - If features remain in `remaining_implications`, the `implied_by` refers to a feature that1015 /// does not exist.1016 ///1017 /// By structuring the code in this way: checking the features defined from each crate one at a1018 /// time, less loading from metadata is performed and thus compiler performance is improved.1019 fn check_features<'tcx>(1020 tcx: TyCtxt<'tcx>,1021 remaining_lib_features: &mut FxIndexMap<Symbol, Span>,1022 remaining_implications: &mut UnordMap<Symbol, Symbol>,1023 defined_features: &LibFeatures,1024 all_implications: &UnordMap<Symbol, Symbol>,1025 ) {1026 for (feature, stability) in defined_features.to_sorted_vec() {1027 if let FeatureStability::AcceptedSince(since) = stability1028 && let Some(span) = remaining_lib_features.get(&feature)1029 {1030 // Mark the feature as enabled, to ensure that it is not marked as unused.1031 let _ = tcx.features().enabled(feature);10321033 // Warn if the user has enabled an already-stable lib feature.1034 if let Some(implies) = all_implications.get(&feature) {1035 unnecessary_partially_stable_feature_lint(tcx, *span, feature, *implies, since);1036 } else {1037 unnecessary_stable_feature_lint(tcx, *span, feature, since);1038 }1039 }1040 // FIXME(#120456) - is `swap_remove` correct?1041 remaining_lib_features.swap_remove(&feature);10421043 // `feature` is the feature doing the implying, but `implied_by` is the feature with1044 // the attribute that establishes this relationship. `implied_by` is guaranteed to be a1045 // feature defined in the local crate because `remaining_implications` is only the1046 // implications from this crate.1047 remaining_implications.remove(&feature);10481049 if let FeatureStability::Unstable { old_name: Some(alias) } = stability1050 && let Some(span) = remaining_lib_features.swap_remove(&alias)1051 {1052 tcx.dcx().emit_err(diagnostics::RenamedFeature { span, feature, alias });1053 }10541055 if remaining_lib_features.is_empty() && remaining_implications.is_empty() {1056 break;1057 }1058 }1059 }10601061 // All local crate implications need to have the feature that implies it confirmed to exist.1062 let mut remaining_implications = tcx.stability_implications(LOCAL_CRATE).clone();10631064 // We always collect the lib features enabled in the current crate, even if there are1065 // no unknown features, because the collection also does feature attribute validation.1066 let local_defined_features = tcx.lib_features(LOCAL_CRATE);1067 if !remaining_lib_features.is_empty() || !remaining_implications.is_empty() {1068 let crates = tcx.crates(());10691070 // Loading the implications of all crates is unavoidable to be able to emit the partial1071 // stabilization diagnostic, but it can be avoided when there are no1072 // `remaining_lib_features`.1073 let mut all_implications = remaining_implications.clone();1074 for &cnum in crates {1075 all_implications1076 .extend_unord(tcx.stability_implications(cnum).items().map(|(k, v)| (*k, *v)));1077 }10781079 check_features(1080 tcx,1081 &mut remaining_lib_features,1082 &mut remaining_implications,1083 local_defined_features,1084 &all_implications,1085 );10861087 for &cnum in crates {1088 if remaining_lib_features.is_empty() && remaining_implications.is_empty() {1089 break;1090 }1091 check_features(1092 tcx,1093 &mut remaining_lib_features,1094 &mut remaining_implications,1095 tcx.lib_features(cnum),1096 &all_implications,1097 );1098 }10991100 if !remaining_lib_features.is_empty() {1101 let lang_features =1102 UNSTABLE_LANG_FEATURES.iter().map(|feature| feature.name).collect::<Vec<_>>();1103 let lib_features = crates1104 .iter()1105 .flat_map(|&cnum| {1106 tcx.lib_features(cnum).stability.keys().copied().into_sorted_stable_ord()1107 })1108 .collect::<Vec<_>>();11091110 let valid_feature_names = [lang_features, lib_features].concat();11111112 // Collect all of the marked as "removed" features1113 let unstable_removed_features = crates1114 .iter()1115 .flat_map(|&cnum| {1116 find_attr!(tcx, cnum.as_def_id(), UnstableRemoved(rem_features) => rem_features)1117 .into_flat_iter()1118 })1119 .collect::<Vec<_>>();11201121 for (feature, span) in remaining_lib_features {1122 if let Some(removed) =1123 unstable_removed_features.iter().find(|removed| removed.feature == feature)1124 {1125 tcx.dcx().emit_err(diagnostics::FeatureRemoved {1126 span,1127 feature,1128 reason: removed.reason,1129 link: removed.link,1130 since: removed.since.to_string(),1131 });1132 } else {1133 let suggestion =1134 feature.find_similar(&valid_feature_names).map(|(actual_name, _)| {1135 diagnostics::MisspelledFeature { span, actual_name }1136 });1137 tcx.dcx().emit_err(diagnostics::UnknownFeature { span, feature, suggestion });1138 }1139 }1140 }1141 }11421143 for (&implied_by, &feature) in remaining_implications.to_sorted_stable_ord() {1144 let local_defined_features = tcx.lib_features(LOCAL_CRATE);1145 let span = local_defined_features1146 .stability1147 .get(&feature)1148 .expect("feature that implied another does not exist")1149 .1;1150 tcx.dcx().emit_err(diagnostics::ImpliedFeatureNotExist { span, feature, implied_by });1151 }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 STABLE_FEATURES,1163 hir::CRATE_HIR_ID,1164 span,1165 diagnostics::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 STABLE_FEATURES,1186 hir::CRATE_HIR_ID,1187 span,1188 diagnostics::UnnecessaryStableFeature { feature, since },1189 );1190}11911192fn duplicate_feature_lint(tcx: TyCtxt<'_>, span: Span, feature: Symbol) {1193 tcx.emit_node_span_lint(1194 DUPLICATE_FEATURES,1195 hir::CRATE_HIR_ID,1196 span,1197 diagnostics::DuplicateFeature { feature },1198 );1199}