1 //! A pass that annotates every item and method with its stability level,
2 //! propagating default levels lexically from parent to children ast nodes.
5 self as attr, ConstStability, Stability, StabilityLevel, Unstable, UnstableReason,
7 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
8 use rustc_errors::{struct_span_err, Applicability};
10 use rustc_hir::def::{DefKind, Res};
11 use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
12 use rustc_hir::hir_id::CRATE_HIR_ID;
13 use rustc_hir::intravisit::{self, Visitor};
14 use rustc_hir::{FieldDef, Item, ItemKind, TraitRef, Ty, TyKind, Variant};
15 use rustc_middle::hir::nested_filter;
16 use rustc_middle::middle::privacy::AccessLevels;
17 use rustc_middle::middle::stability::{AllowUnstable, DeprecationEntry, Index};
18 use rustc_middle::ty::{query::Providers, TyCtxt};
19 use rustc_session::lint;
20 use rustc_session::lint::builtin::{INEFFECTIVE_UNSTABLE_TRAIT_IMPL, USELESS_DEPRECATED};
21 use rustc_session::Session;
22 use rustc_span::symbol::{sym, Symbol};
24 use rustc_target::spec::abi::Abi;
26 use std::cmp::Ordering;
28 use std::mem::replace;
29 use std::num::NonZeroU32;
33 /// Annotation is required if not inherited from unstable parents.
35 /// Annotation is useless, reject it.
37 /// Deprecation annotation is useless, reject it. (Stability attribute is still required.)
38 DeprecationProhibited,
39 /// Annotation itself is useless, but it can be propagated to children.
43 /// Whether to inherit deprecation flags for nested items. In most cases, we do want to inherit
44 /// deprecation, because nested items rarely have individual deprecation attributes, and so
45 /// should be treated as deprecated if their parent is. However, default generic parameters
46 /// have separate deprecation attributes from their parents, so we do not wish to inherit
47 /// deprecation in this case. For example, inheriting deprecation for `T` in `Foo<T>`
48 /// would cause a duplicate warning arising from both `Foo` and `T` being deprecated.
50 enum InheritDeprecation {
55 impl InheritDeprecation {
56 fn yes(&self) -> bool {
57 matches!(self, InheritDeprecation::Yes)
61 /// Whether to inherit const stability flags for nested items. In most cases, we do not want to
62 /// inherit const stability: just because an enclosing `fn` is const-stable does not mean
63 /// all `extern` imports declared in it should be const-stable! However, trait methods
64 /// inherit const stability attributes from their parent and do not have their own.
65 enum InheritConstStability {
70 impl InheritConstStability {
71 fn yes(&self) -> bool {
72 matches!(self, InheritConstStability::Yes)
76 enum InheritStability {
81 impl InheritStability {
82 fn yes(&self) -> bool {
83 matches!(self, InheritStability::Yes)
87 /// A private tree-walker for producing an `Index`.
88 struct Annotator<'a, 'tcx> {
91 parent_stab: Option<Stability>,
92 parent_const_stab: Option<ConstStability>,
93 parent_depr: Option<DeprecationEntry>,
97 impl<'a, 'tcx> Annotator<'a, 'tcx> {
98 /// Determine the stability for a node based on its attributes and inherited stability. The
99 /// stability is recorded in the index and used as the parent. If the node is a function,
100 /// `fn_sig` is its signature.
105 fn_sig: Option<&'tcx hir::FnSig<'tcx>>,
106 kind: AnnotationKind,
107 inherit_deprecation: InheritDeprecation,
108 inherit_const_stability: InheritConstStability,
109 inherit_from_parent: InheritStability,
112 F: FnOnce(&mut Self),
114 let attrs = self.tcx.hir().attrs(self.tcx.hir().local_def_id_to_hir_id(def_id));
115 debug!("annotate(id = {:?}, attrs = {:?})", def_id, attrs);
117 let depr = attr::find_deprecation(&self.tcx.sess, attrs);
118 let mut is_deprecated = false;
119 if let Some((depr, span)) = &depr {
120 is_deprecated = true;
122 if kind == AnnotationKind::Prohibited || kind == AnnotationKind::DeprecationProhibited {
123 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
124 self.tcx.struct_span_lint_hir(USELESS_DEPRECATED, hir_id, *span, |lint| {
125 lint.build("this `#[deprecated]` annotation has no effect")
126 .span_suggestion_short(
128 "remove the unnecessary deprecation attribute",
130 rustc_errors::Applicability::MachineApplicable,
136 // `Deprecation` is just two pointers, no need to intern it
137 let depr_entry = DeprecationEntry::local(*depr, def_id);
138 self.index.depr_map.insert(def_id, depr_entry);
139 } else if let Some(parent_depr) = self.parent_depr {
140 if inherit_deprecation.yes() {
141 is_deprecated = true;
142 info!("tagging child {:?} as deprecated from parent", def_id);
143 self.index.depr_map.insert(def_id, parent_depr);
147 if !self.tcx.features().staged_api {
148 // Propagate unstability. This can happen even for non-staged-api crates in case
149 // -Zforce-unstable-if-unmarked is set.
150 if let Some(stab) = self.parent_stab {
151 if inherit_deprecation.yes() && stab.is_unstable() {
152 self.index.stab_map.insert(def_id, stab);
156 self.recurse_with_stability_attrs(
157 depr.map(|(d, _)| DeprecationEntry::local(d, def_id)),
165 let (stab, const_stab, body_stab) = attr::find_stability(&self.tcx.sess, attrs, item_sp);
166 let mut const_span = None;
168 let const_stab = const_stab.map(|(const_stab, const_span_node)| {
169 self.index.const_stab_map.insert(def_id, const_stab);
170 const_span = Some(const_span_node);
174 // If the current node is a function, has const stability attributes and if it doesn not have an intrinsic ABI,
175 // check if the function/method is const or the parent impl block is const
176 if let (Some(const_span), Some(fn_sig)) = (const_span, fn_sig) {
177 if fn_sig.header.abi != Abi::RustIntrinsic
178 && fn_sig.header.abi != Abi::PlatformIntrinsic
179 && !fn_sig.header.is_const()
181 if !self.in_trait_impl
182 || (self.in_trait_impl && !self.tcx.is_const_fn_raw(def_id.to_def_id()))
184 missing_const_err(&self.tcx.sess, fn_sig.span, const_span);
189 // `impl const Trait for Type` items forward their const stability to their
190 // immediate children.
191 if const_stab.is_none() {
192 debug!("annotate: const_stab not found, parent = {:?}", self.parent_const_stab);
193 if let Some(parent) = self.parent_const_stab {
194 if parent.is_const_unstable() {
195 self.index.const_stab_map.insert(def_id, parent);
200 if let Some((rustc_attr::Deprecation { is_since_rustc_version: true, .. }, span)) = &depr {
206 "deprecated attribute must be paired with \
207 either stable or unstable attribute"
213 if let Some((body_stab, _span)) = body_stab {
214 // FIXME: check that this item can have body stability
216 self.index.default_body_stab_map.insert(def_id, body_stab);
217 debug!(?self.index.default_body_stab_map);
220 let stab = stab.map(|(stab, span)| {
221 // Error if prohibited, or can't inherit anything from a container.
222 if kind == AnnotationKind::Prohibited
223 || (kind == AnnotationKind::Container && stab.level.is_stable() && is_deprecated)
225 self.tcx.sess.struct_span_err(span,"this stability annotation is useless")
226 .span_label(span, "useless stability annotation")
227 .span_label(item_sp, "the stability attribute annotates this item")
231 debug!("annotate: found {:?}", stab);
233 // Check if deprecated_since < stable_since. If it is,
234 // this is *almost surely* an accident.
235 if let (&Some(dep_since), &attr::Stable { since: stab_since, .. }) =
236 (&depr.as_ref().and_then(|(d, _)| d.since), &stab.level)
238 // Explicit version of iter::order::lt to handle parse errors properly
239 for (dep_v, stab_v) in
240 iter::zip(dep_since.as_str().split('.'), stab_since.as_str().split('.'))
242 match stab_v.parse::<u64>() {
244 self.tcx.sess.struct_span_err(span, "invalid stability version found")
245 .span_label(span, "invalid stability version")
246 .span_label(item_sp, "the stability attribute annotates this item")
250 Ok(stab_vp) => match dep_v.parse::<u64>() {
251 Ok(dep_vp) => match dep_vp.cmp(&stab_vp) {
253 self.tcx.sess.struct_span_err(span, "an API can't be stabilized after it is deprecated")
254 .span_label(span, "invalid version")
255 .span_label(item_sp, "the stability attribute annotates this item")
259 Ordering::Equal => continue,
260 Ordering::Greater => break,
264 self.tcx.sess.struct_span_err(span, "invalid deprecation version found")
265 .span_label(span, "invalid deprecation version")
266 .span_label(item_sp, "the stability attribute annotates this item")
276 if let Stability { level: Unstable { implied_by: Some(implied_by), .. }, feature } = stab {
277 self.index.implications.insert(implied_by, feature);
280 self.index.stab_map.insert(def_id, stab);
285 debug!("annotate: stab not found, parent = {:?}", self.parent_stab);
286 if let Some(stab) = self.parent_stab {
287 if inherit_deprecation.yes() && stab.is_unstable() || inherit_from_parent.yes() {
288 self.index.stab_map.insert(def_id, stab);
293 self.recurse_with_stability_attrs(
294 depr.map(|(d, _)| DeprecationEntry::local(d, def_id)),
296 if inherit_const_stability.yes() { const_stab } else { None },
301 fn recurse_with_stability_attrs(
303 depr: Option<DeprecationEntry>,
304 stab: Option<Stability>,
305 const_stab: Option<ConstStability>,
306 f: impl FnOnce(&mut Self),
308 // These will be `Some` if this item changes the corresponding stability attribute.
309 let mut replaced_parent_depr = None;
310 let mut replaced_parent_stab = None;
311 let mut replaced_parent_const_stab = None;
313 if let Some(depr) = depr {
314 replaced_parent_depr = Some(replace(&mut self.parent_depr, Some(depr)));
316 if let Some(stab) = stab {
317 replaced_parent_stab = Some(replace(&mut self.parent_stab, Some(stab)));
319 if let Some(const_stab) = const_stab {
320 replaced_parent_const_stab =
321 Some(replace(&mut self.parent_const_stab, Some(const_stab)));
326 if let Some(orig_parent_depr) = replaced_parent_depr {
327 self.parent_depr = orig_parent_depr;
329 if let Some(orig_parent_stab) = replaced_parent_stab {
330 self.parent_stab = orig_parent_stab;
332 if let Some(orig_parent_const_stab) = replaced_parent_const_stab {
333 self.parent_const_stab = orig_parent_const_stab;
338 impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
339 /// Because stability levels are scoped lexically, we want to walk
340 /// nested items in the context of the outer item, so enable
342 type NestedFilter = nested_filter::All;
344 fn nested_visit_map(&mut self) -> Self::Map {
348 fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
349 let orig_in_trait_impl = self.in_trait_impl;
350 let mut kind = AnnotationKind::Required;
351 let mut const_stab_inherit = InheritConstStability::No;
352 let mut fn_sig = None;
355 // Inherent impls and foreign modules serve only as containers for other items,
356 // they don't have their own stability. They still can be annotated as unstable
357 // and propagate this instability to children, but this annotation is completely
358 // optional. They inherit stability from their parents when unannotated.
359 hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
360 | hir::ItemKind::ForeignMod { .. } => {
361 self.in_trait_impl = false;
362 kind = AnnotationKind::Container;
364 hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => {
365 self.in_trait_impl = true;
366 kind = AnnotationKind::DeprecationProhibited;
367 const_stab_inherit = InheritConstStability::Yes;
369 hir::ItemKind::Struct(ref sd, _) => {
370 if let Some(ctor_hir_id) = sd.ctor_hir_id() {
372 self.tcx.hir().local_def_id(ctor_hir_id),
375 AnnotationKind::Required,
376 InheritDeprecation::Yes,
377 InheritConstStability::No,
378 InheritStability::Yes,
383 hir::ItemKind::Fn(ref item_fn_sig, _, _) => {
384 fn_sig = Some(item_fn_sig);
394 InheritDeprecation::Yes,
396 InheritStability::No,
397 |v| intravisit::walk_item(v, i),
399 self.in_trait_impl = orig_in_trait_impl;
402 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
403 let fn_sig = match ti.kind {
404 hir::TraitItemKind::Fn(ref fn_sig, _) => Some(fn_sig),
412 AnnotationKind::Required,
413 InheritDeprecation::Yes,
414 InheritConstStability::No,
415 InheritStability::No,
417 intravisit::walk_trait_item(v, ti);
422 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
424 if self.in_trait_impl { AnnotationKind::Prohibited } else { AnnotationKind::Required };
426 let fn_sig = match ii.kind {
427 hir::ImplItemKind::Fn(ref fn_sig, _) => Some(fn_sig),
436 InheritDeprecation::Yes,
437 InheritConstStability::No,
438 InheritStability::No,
440 intravisit::walk_impl_item(v, ii);
445 fn visit_variant(&mut self, var: &'tcx Variant<'tcx>) {
447 self.tcx.hir().local_def_id(var.id),
450 AnnotationKind::Required,
451 InheritDeprecation::Yes,
452 InheritConstStability::No,
453 InheritStability::Yes,
455 if let Some(ctor_hir_id) = var.data.ctor_hir_id() {
457 v.tcx.hir().local_def_id(ctor_hir_id),
460 AnnotationKind::Required,
461 InheritDeprecation::Yes,
462 InheritConstStability::No,
463 InheritStability::No,
468 intravisit::walk_variant(v, var)
473 fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
475 self.tcx.hir().local_def_id(s.hir_id),
478 AnnotationKind::Required,
479 InheritDeprecation::Yes,
480 InheritConstStability::No,
481 InheritStability::Yes,
483 intravisit::walk_field_def(v, s);
488 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
493 AnnotationKind::Required,
494 InheritDeprecation::Yes,
495 InheritConstStability::No,
496 InheritStability::No,
498 intravisit::walk_foreign_item(v, i);
503 fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
504 let kind = match &p.kind {
505 // Allow stability attributes on default generic arguments.
506 hir::GenericParamKind::Type { default: Some(_), .. }
507 | hir::GenericParamKind::Const { default: Some(_), .. } => AnnotationKind::Container,
508 _ => AnnotationKind::Prohibited,
512 self.tcx.hir().local_def_id(p.hir_id),
516 InheritDeprecation::No,
517 InheritConstStability::No,
518 InheritStability::No,
520 intravisit::walk_generic_param(v, p);
526 struct MissingStabilityAnnotations<'tcx> {
528 access_levels: &'tcx AccessLevels,
531 impl<'tcx> MissingStabilityAnnotations<'tcx> {
532 fn check_missing_stability(&self, def_id: LocalDefId, span: Span) {
533 let stab = self.tcx.stability().local_stability(def_id);
534 if !self.tcx.sess.opts.test && stab.is_none() && self.access_levels.is_reachable(def_id) {
535 let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
536 self.tcx.sess.span_err(span, &format!("{} has missing stability attribute", descr));
540 fn check_missing_const_stability(&self, def_id: LocalDefId, span: Span) {
541 if !self.tcx.features().staged_api {
545 let is_const = self.tcx.is_const_fn(def_id.to_def_id())
546 || self.tcx.is_const_trait_impl_raw(def_id.to_def_id());
549 .lookup_stability(def_id)
550 .map_or(false, |stability| stability.level.is_stable());
551 let missing_const_stability_attribute = self.tcx.lookup_const_stability(def_id).is_none();
552 let is_reachable = self.access_levels.is_reachable(def_id);
554 if is_const && is_stable && missing_const_stability_attribute && is_reachable {
555 let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
556 self.tcx.sess.span_err(span, &format!("{descr} has missing const stability attribute"));
561 impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> {
562 type NestedFilter = nested_filter::OnlyBodies;
564 fn nested_visit_map(&mut self) -> Self::Map {
568 fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
569 // Inherent impls and foreign modules serve only as containers for other items,
570 // they don't have their own stability. They still can be annotated as unstable
571 // and propagate this instability to children, but this annotation is completely
572 // optional. They inherit stability from their parents when unannotated.
575 hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
576 | hir::ItemKind::ForeignMod { .. }
578 self.check_missing_stability(i.def_id, i.span);
581 // Ensure stable `const fn` have a const stability attribute.
582 self.check_missing_const_stability(i.def_id, i.span);
584 intravisit::walk_item(self, i)
587 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
588 self.check_missing_stability(ti.def_id, ti.span);
589 intravisit::walk_trait_item(self, ti);
592 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
593 let impl_def_id = self.tcx.hir().get_parent_item(ii.hir_id());
594 if self.tcx.impl_trait_ref(impl_def_id).is_none() {
595 self.check_missing_stability(ii.def_id, ii.span);
596 self.check_missing_const_stability(ii.def_id, ii.span);
598 intravisit::walk_impl_item(self, ii);
601 fn visit_variant(&mut self, var: &'tcx Variant<'tcx>) {
602 self.check_missing_stability(self.tcx.hir().local_def_id(var.id), var.span);
603 intravisit::walk_variant(self, var);
606 fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
607 self.check_missing_stability(self.tcx.hir().local_def_id(s.hir_id), s.span);
608 intravisit::walk_field_def(self, s);
611 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
612 self.check_missing_stability(i.def_id, i.span);
613 intravisit::walk_foreign_item(self, i);
615 // Note that we don't need to `check_missing_stability` for default generic parameters,
616 // as we assume that any default generic parameters without attributes are automatically
617 // stable (assuming they have not inherited instability from their parent).
620 fn stability_index(tcx: TyCtxt<'_>, (): ()) -> Index {
621 let mut index = Index {
622 stab_map: Default::default(),
623 const_stab_map: Default::default(),
624 default_body_stab_map: Default::default(),
625 depr_map: Default::default(),
626 implications: Default::default(),
630 let mut annotator = Annotator {
634 parent_const_stab: None,
636 in_trait_impl: false,
639 // If the `-Z force-unstable-if-unmarked` flag is passed then we provide
640 // a parent stability annotation which indicates that this is private
641 // with the `rustc_private` feature. This is intended for use when
642 // compiling `librustc_*` crates themselves so we can leverage crates.io
643 // while maintaining the invariant that all sysroot crates are unstable
644 // by default and are unable to be used.
645 if tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
646 let stability = Stability {
647 level: attr::StabilityLevel::Unstable {
648 reason: UnstableReason::Default,
649 issue: NonZeroU32::new(27812),
653 feature: sym::rustc_private,
655 annotator.parent_stab = Some(stability);
660 tcx.hir().span(CRATE_HIR_ID),
662 AnnotationKind::Required,
663 InheritDeprecation::Yes,
664 InheritConstStability::No,
665 InheritStability::No,
666 |v| tcx.hir().walk_toplevel_module(v),
672 /// Cross-references the feature names of unstable APIs with enabled
673 /// features and possibly prints errors.
674 fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
675 tcx.hir().visit_item_likes_in_module(module_def_id, &mut Checker { tcx });
678 pub(crate) fn provide(providers: &mut Providers) {
679 *providers = Providers {
680 check_mod_unstable_api_usage,
682 stability_implications: |tcx, _| tcx.stability().implications.clone(),
683 lookup_stability: |tcx, id| tcx.stability().local_stability(id.expect_local()),
684 lookup_const_stability: |tcx, id| tcx.stability().local_const_stability(id.expect_local()),
685 lookup_default_body_stability: |tcx, id| {
686 tcx.stability().local_default_body_stability(id.expect_local())
688 lookup_deprecation_entry: |tcx, id| {
689 tcx.stability().local_deprecation_entry(id.expect_local())
695 struct Checker<'tcx> {
699 impl<'tcx> Visitor<'tcx> for Checker<'tcx> {
700 type NestedFilter = nested_filter::OnlyBodies;
702 /// Because stability levels are scoped lexically, we want to walk
703 /// nested items in the context of the outer item, so enable
705 fn nested_visit_map(&mut self) -> Self::Map {
709 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
711 hir::ItemKind::ExternCrate(_) => {
712 // compiler-generated `extern crate` items have a dummy span.
713 // `std` is still checked for the `restricted-std` feature.
714 if item.span.is_dummy() && item.ident.name != sym::std {
718 let Some(cnum) = self.tcx.extern_mod_stmt_cnum(item.def_id) else {
721 let def_id = cnum.as_def_id();
722 self.tcx.check_stability(def_id, Some(item.hir_id()), item.span, None);
725 // For implementations of traits, check the stability of each item
726 // individually as it's possible to have a stable trait with unstable
728 hir::ItemKind::Impl(hir::Impl {
729 of_trait: Some(ref t),
735 let features = self.tcx.features();
736 if features.staged_api {
737 let attrs = self.tcx.hir().attrs(item.hir_id());
738 let (stab, const_stab, _) =
739 attr::find_stability(&self.tcx.sess, attrs, item.span);
741 // If this impl block has an #[unstable] attribute, give an
742 // error if all involved types and traits are stable, because
743 // it will have no effect.
744 // See: https://github.com/rust-lang/rust/issues/55436
745 if let Some((Stability { level: attr::Unstable { .. }, .. }, span)) = stab {
746 let mut c = CheckTraitImplStable { tcx: self.tcx, fully_stable: true };
748 c.visit_trait_ref(t);
750 self.tcx.struct_span_lint_hir(
751 INEFFECTIVE_UNSTABLE_TRAIT_IMPL,
755 .build("an `#[unstable]` annotation here has no effect")
756 .note("see issue #55436 <https://github.com/rust-lang/rust/issues/55436> for more information")
762 // `#![feature(const_trait_impl)]` is unstable, so any impl declared stable
763 // needs to have an error emitted.
764 if features.const_trait_impl
765 && *constness == hir::Constness::Const
766 && const_stab.map_or(false, |(stab, _)| stab.is_const_stable())
770 .struct_span_err(item.span, "trait implementations cannot be const stable yet")
771 .note("see issue #67792 <https://github.com/rust-lang/rust/issues/67792> for more information")
776 for impl_item_ref in *items {
777 let impl_item = self.tcx.associated_item(impl_item_ref.id.def_id);
779 if let Some(def_id) = impl_item.trait_item_def_id {
780 // Pass `None` to skip deprecation warnings.
781 self.tcx.check_stability(def_id, None, impl_item_ref.span, None);
788 intravisit::walk_item(self, item);
791 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, id: hir::HirId) {
792 if let Some(def_id) = path.res.opt_def_id() {
793 let method_span = path.segments.last().map(|s| s.ident.span);
794 let item_is_allowed = self.tcx.check_stability_allow_unstable(
799 if is_unstable_reexport(self.tcx, id) {
806 let is_allowed_through_unstable_modules = |def_id| {
808 .lookup_stability(def_id)
809 .map(|stab| match stab.level {
810 StabilityLevel::Stable { allowed_through_unstable_modules, .. } => {
811 allowed_through_unstable_modules
818 if item_is_allowed && !is_allowed_through_unstable_modules(def_id) {
819 // Check parent modules stability as well if the item the path refers to is itself
820 // stable. We only emit warnings for unstable path segments if the item is stable
821 // or allowed because stability is often inherited, so the most common case is that
822 // both the segments and the item are unstable behind the same feature flag.
824 // We check here rather than in `visit_path_segment` to prevent visiting the last
825 // path segment twice
827 // We include special cases via #[rustc_allowed_through_unstable_modules] for items
828 // that were accidentally stabilized through unstable paths before this check was
829 // added, such as `core::intrinsics::transmute`
830 let parents = path.segments.iter().rev().skip(1);
831 for path_segment in parents {
832 if let Some(def_id) = path_segment.res.as_ref().and_then(Res::opt_def_id) {
833 // use `None` for id to prevent deprecation check
834 self.tcx.check_stability_allow_unstable(
839 if is_unstable_reexport(self.tcx, id) {
850 intravisit::walk_path(self, path)
854 /// Check whether a path is a `use` item that has been marked as unstable.
856 /// See issue #94972 for details on why this is a special case
857 fn is_unstable_reexport<'tcx>(tcx: TyCtxt<'tcx>, id: hir::HirId) -> bool {
858 // Get the LocalDefId so we can lookup the item to check the kind.
859 let Some(def_id) = tcx.hir().opt_local_def_id(id) else { return false; };
861 let Some(stab) = tcx.stability().local_stability(def_id) else {
865 if stab.level.is_stable() {
866 // The re-export is not marked as unstable, don't override
870 // If this is a path that isn't a use, we don't need to do anything special
871 if !matches!(tcx.hir().item(hir::ItemId { def_id }).kind, ItemKind::Use(..)) {
878 struct CheckTraitImplStable<'tcx> {
883 impl<'tcx> Visitor<'tcx> for CheckTraitImplStable<'tcx> {
884 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _id: hir::HirId) {
885 if let Some(def_id) = path.res.opt_def_id() {
886 if let Some(stab) = self.tcx.lookup_stability(def_id) {
887 self.fully_stable &= stab.level.is_stable();
890 intravisit::walk_path(self, path)
893 fn visit_trait_ref(&mut self, t: &'tcx TraitRef<'tcx>) {
894 if let Res::Def(DefKind::Trait, trait_did) = t.path.res {
895 if let Some(stab) = self.tcx.lookup_stability(trait_did) {
896 self.fully_stable &= stab.level.is_stable();
899 intravisit::walk_trait_ref(self, t)
902 fn visit_ty(&mut self, t: &'tcx Ty<'tcx>) {
903 if let TyKind::Never = t.kind {
904 self.fully_stable = false;
906 intravisit::walk_ty(self, t)
910 /// Given the list of enabled features that were not language features (i.e., that
911 /// were expected to be library features), and the list of features used from
912 /// libraries, identify activated features that don't exist and error about them.
913 pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {
915 tcx.sess.opts.unstable_opts.force_unstable_if_unmarked || tcx.features().staged_api;
917 let access_levels = &tcx.privacy_access_levels(());
918 let mut missing = MissingStabilityAnnotations { tcx, access_levels };
919 missing.check_missing_stability(CRATE_DEF_ID, tcx.hir().span(CRATE_HIR_ID));
920 tcx.hir().walk_toplevel_module(&mut missing);
921 tcx.hir().visit_all_item_likes_in_crate(&mut missing);
924 let declared_lang_features = &tcx.features().declared_lang_features;
925 let mut lang_features = FxHashSet::default();
926 for &(feature, span, since) in declared_lang_features {
927 if let Some(since) = since {
928 // Warn if the user has enabled an already-stable lang feature.
929 unnecessary_stable_feature_lint(tcx, span, feature, since);
931 if !lang_features.insert(feature) {
932 // Warn if the user enables a lang feature multiple times.
933 duplicate_feature_err(tcx.sess, span, feature);
937 let declared_lib_features = &tcx.features().declared_lib_features;
938 let mut remaining_lib_features = FxIndexMap::default();
939 for (feature, span) in declared_lib_features {
940 if !tcx.sess.opts.unstable_features.is_nightly_build() {
945 "`#![feature]` may not be used on the {} release channel",
946 env!("CFG_RELEASE_CHANNEL")
950 if remaining_lib_features.contains_key(&feature) {
951 // Warn if the user enables a lib feature multiple times.
952 duplicate_feature_err(tcx.sess, *span, *feature);
954 remaining_lib_features.insert(feature, *span);
956 // `stdbuild` has special handling for `libc`, so we need to
957 // recognise the feature when building std.
958 // Likewise, libtest is handled specially, so `test` isn't
959 // available as we'd like it to be.
960 // FIXME: only remove `libc` when `stdbuild` is active.
961 // FIXME: remove special casing for `test`.
962 remaining_lib_features.remove(&sym::libc);
963 remaining_lib_features.remove(&sym::test);
965 // We always collect the lib features declared in the current crate, even if there are
966 // no unknown features, because the collection also does feature attribute validation.
967 let local_defined_features = tcx.lib_features(());
968 let mut all_lib_features: FxHashMap<_, _> =
969 local_defined_features.to_vec().iter().map(|el| *el).collect();
970 let mut implications = tcx.stability_implications(rustc_hir::def_id::LOCAL_CRATE).clone();
971 for &cnum in tcx.crates(()) {
972 implications.extend(tcx.stability_implications(cnum));
973 all_lib_features.extend(tcx.defined_lib_features(cnum).iter().map(|el| *el));
976 // Check that every feature referenced by an `implied_by` exists (for features defined in the
978 for (implied_by, feature) in tcx.stability_implications(rustc_hir::def_id::LOCAL_CRATE) {
979 // Only `implied_by` needs to be checked, `feature` is guaranteed to exist.
980 if !all_lib_features.contains_key(implied_by) {
981 let span = local_defined_features
984 .map(|(_, span)| span)
985 .or_else(|| local_defined_features.unstable.get(feature))
986 .expect("feature that implied another does not exist");
990 format!("feature `{implied_by}` implying `{feature}` does not exist"),
996 if !remaining_lib_features.is_empty() {
997 for (feature, since) in all_lib_features.iter() {
998 if let Some(since) = since && let Some(span) = remaining_lib_features.get(&feature) {
999 // Warn if the user has enabled an already-stable lib feature.
1000 if let Some(implies) = implications.get(&feature) {
1001 unnecessary_partially_stable_feature_lint(tcx, *span, *feature, *implies, *since);
1003 unnecessary_stable_feature_lint(tcx, *span, *feature, *since);
1006 remaining_lib_features.remove(&feature);
1007 if remaining_lib_features.is_empty() {
1013 for (feature, span) in remaining_lib_features {
1014 struct_span_err!(tcx.sess, span, E0635, "unknown feature `{}`", feature).emit();
1017 // FIXME(#44232): the `used_features` table no longer exists, so we
1018 // don't lint about unused features. We should re-enable this one day!
1021 fn unnecessary_partially_stable_feature_lint(
1028 tcx.struct_span_lint_hir(lint::builtin::STABLE_FEATURES, hir::CRATE_HIR_ID, span, |lint| {
1029 lint.build(&format!(
1030 "the feature `{feature}` has been partially stabilized since {since} and is succeeded \
1031 by the feature `{implies}`"
1036 "if you are using features which are still unstable, change to using `{implies}`"
1039 Applicability::MaybeIncorrect,
1042 tcx.sess.source_map().span_extend_to_line(span),
1043 "if you are using features which are now stable, remove this line",
1045 Applicability::MaybeIncorrect,
1051 fn unnecessary_stable_feature_lint(tcx: TyCtxt<'_>, span: Span, feature: Symbol, since: Symbol) {
1052 tcx.struct_span_lint_hir(lint::builtin::STABLE_FEATURES, hir::CRATE_HIR_ID, span, |lint| {
1053 lint.build(&format!(
1054 "the feature `{feature}` has been stable since {since} and no longer requires an \
1055 attribute to enable",
1061 fn duplicate_feature_err(sess: &Session, span: Span, feature: Symbol) {
1062 struct_span_err!(sess, span, E0636, "the feature `{}` has already been declared", feature)
1066 fn missing_const_err(session: &Session, fn_sig_span: Span, const_span: Span) {
1067 const ERROR_MSG: &'static str = "attributes `#[rustc_const_unstable]` \
1068 and `#[rustc_const_stable]` require \
1069 the function or method to be `const`";
1072 .struct_span_err(fn_sig_span, ERROR_MSG)
1073 .span_help(fn_sig_span, "make the function or method const")
1074 .span_label(const_span, "attribute specified here")