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::Yes,
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 if let Some(ctor_hir_id) = var.data.ctor_hir_id() {
604 self.check_missing_stability(self.tcx.hir().local_def_id(ctor_hir_id), var.span);
606 intravisit::walk_variant(self, var);
609 fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
610 self.check_missing_stability(self.tcx.hir().local_def_id(s.hir_id), s.span);
611 intravisit::walk_field_def(self, s);
614 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
615 self.check_missing_stability(i.def_id, i.span);
616 intravisit::walk_foreign_item(self, i);
618 // Note that we don't need to `check_missing_stability` for default generic parameters,
619 // as we assume that any default generic parameters without attributes are automatically
620 // stable (assuming they have not inherited instability from their parent).
623 fn stability_index(tcx: TyCtxt<'_>, (): ()) -> Index {
624 let mut index = Index {
625 stab_map: Default::default(),
626 const_stab_map: Default::default(),
627 default_body_stab_map: Default::default(),
628 depr_map: Default::default(),
629 implications: Default::default(),
633 let mut annotator = Annotator {
637 parent_const_stab: None,
639 in_trait_impl: false,
642 // If the `-Z force-unstable-if-unmarked` flag is passed then we provide
643 // a parent stability annotation which indicates that this is private
644 // with the `rustc_private` feature. This is intended for use when
645 // compiling `librustc_*` crates themselves so we can leverage crates.io
646 // while maintaining the invariant that all sysroot crates are unstable
647 // by default and are unable to be used.
648 if tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
649 let stability = Stability {
650 level: attr::StabilityLevel::Unstable {
651 reason: UnstableReason::Default,
652 issue: NonZeroU32::new(27812),
656 feature: sym::rustc_private,
658 annotator.parent_stab = Some(stability);
663 tcx.hir().span(CRATE_HIR_ID),
665 AnnotationKind::Required,
666 InheritDeprecation::Yes,
667 InheritConstStability::No,
668 InheritStability::No,
669 |v| tcx.hir().walk_toplevel_module(v),
675 /// Cross-references the feature names of unstable APIs with enabled
676 /// features and possibly prints errors.
677 fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
678 tcx.hir().visit_item_likes_in_module(module_def_id, &mut Checker { tcx });
681 pub(crate) fn provide(providers: &mut Providers) {
682 *providers = Providers {
683 check_mod_unstable_api_usage,
685 stability_implications: |tcx, _| tcx.stability().implications.clone(),
686 lookup_stability: |tcx, id| tcx.stability().local_stability(id.expect_local()),
687 lookup_const_stability: |tcx, id| tcx.stability().local_const_stability(id.expect_local()),
688 lookup_default_body_stability: |tcx, id| {
689 tcx.stability().local_default_body_stability(id.expect_local())
691 lookup_deprecation_entry: |tcx, id| {
692 tcx.stability().local_deprecation_entry(id.expect_local())
698 struct Checker<'tcx> {
702 impl<'tcx> Visitor<'tcx> for Checker<'tcx> {
703 type NestedFilter = nested_filter::OnlyBodies;
705 /// Because stability levels are scoped lexically, we want to walk
706 /// nested items in the context of the outer item, so enable
708 fn nested_visit_map(&mut self) -> Self::Map {
712 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
714 hir::ItemKind::ExternCrate(_) => {
715 // compiler-generated `extern crate` items have a dummy span.
716 // `std` is still checked for the `restricted-std` feature.
717 if item.span.is_dummy() && item.ident.name != sym::std {
721 let Some(cnum) = self.tcx.extern_mod_stmt_cnum(item.def_id) else {
724 let def_id = cnum.as_def_id();
725 self.tcx.check_stability(def_id, Some(item.hir_id()), item.span, None);
728 // For implementations of traits, check the stability of each item
729 // individually as it's possible to have a stable trait with unstable
731 hir::ItemKind::Impl(hir::Impl {
732 of_trait: Some(ref t),
738 let features = self.tcx.features();
739 if features.staged_api {
740 let attrs = self.tcx.hir().attrs(item.hir_id());
741 let (stab, const_stab, _) =
742 attr::find_stability(&self.tcx.sess, attrs, item.span);
744 // If this impl block has an #[unstable] attribute, give an
745 // error if all involved types and traits are stable, because
746 // it will have no effect.
747 // See: https://github.com/rust-lang/rust/issues/55436
748 if let Some((Stability { level: attr::Unstable { .. }, .. }, span)) = stab {
749 let mut c = CheckTraitImplStable { tcx: self.tcx, fully_stable: true };
751 c.visit_trait_ref(t);
753 self.tcx.struct_span_lint_hir(
754 INEFFECTIVE_UNSTABLE_TRAIT_IMPL,
758 .build("an `#[unstable]` annotation here has no effect")
759 .note("see issue #55436 <https://github.com/rust-lang/rust/issues/55436> for more information")
765 // `#![feature(const_trait_impl)]` is unstable, so any impl declared stable
766 // needs to have an error emitted.
767 if features.const_trait_impl
768 && *constness == hir::Constness::Const
769 && const_stab.map_or(false, |(stab, _)| stab.is_const_stable())
773 .struct_span_err(item.span, "trait implementations cannot be const stable yet")
774 .note("see issue #67792 <https://github.com/rust-lang/rust/issues/67792> for more information")
779 for impl_item_ref in *items {
780 let impl_item = self.tcx.associated_item(impl_item_ref.id.def_id);
782 if let Some(def_id) = impl_item.trait_item_def_id {
783 // Pass `None` to skip deprecation warnings.
784 self.tcx.check_stability(def_id, None, impl_item_ref.span, None);
791 intravisit::walk_item(self, item);
794 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, id: hir::HirId) {
795 if let Some(def_id) = path.res.opt_def_id() {
796 let method_span = path.segments.last().map(|s| s.ident.span);
797 let item_is_allowed = self.tcx.check_stability_allow_unstable(
802 if is_unstable_reexport(self.tcx, id) {
809 let is_allowed_through_unstable_modules = |def_id| {
811 .lookup_stability(def_id)
812 .map(|stab| match stab.level {
813 StabilityLevel::Stable { allowed_through_unstable_modules, .. } => {
814 allowed_through_unstable_modules
821 if item_is_allowed && !is_allowed_through_unstable_modules(def_id) {
822 // Check parent modules stability as well if the item the path refers to is itself
823 // stable. We only emit warnings for unstable path segments if the item is stable
824 // or allowed because stability is often inherited, so the most common case is that
825 // both the segments and the item are unstable behind the same feature flag.
827 // We check here rather than in `visit_path_segment` to prevent visiting the last
828 // path segment twice
830 // We include special cases via #[rustc_allowed_through_unstable_modules] for items
831 // that were accidentally stabilized through unstable paths before this check was
832 // added, such as `core::intrinsics::transmute`
833 let parents = path.segments.iter().rev().skip(1);
834 for path_segment in parents {
835 if let Some(def_id) = path_segment.res.as_ref().and_then(Res::opt_def_id) {
836 // use `None` for id to prevent deprecation check
837 self.tcx.check_stability_allow_unstable(
842 if is_unstable_reexport(self.tcx, id) {
853 intravisit::walk_path(self, path)
857 /// Check whether a path is a `use` item that has been marked as unstable.
859 /// See issue #94972 for details on why this is a special case
860 fn is_unstable_reexport<'tcx>(tcx: TyCtxt<'tcx>, id: hir::HirId) -> bool {
861 // Get the LocalDefId so we can lookup the item to check the kind.
862 let Some(def_id) = tcx.hir().opt_local_def_id(id) else { return false; };
864 let Some(stab) = tcx.stability().local_stability(def_id) else {
868 if stab.level.is_stable() {
869 // The re-export is not marked as unstable, don't override
873 // If this is a path that isn't a use, we don't need to do anything special
874 if !matches!(tcx.hir().item(hir::ItemId { def_id }).kind, ItemKind::Use(..)) {
881 struct CheckTraitImplStable<'tcx> {
886 impl<'tcx> Visitor<'tcx> for CheckTraitImplStable<'tcx> {
887 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _id: hir::HirId) {
888 if let Some(def_id) = path.res.opt_def_id() {
889 if let Some(stab) = self.tcx.lookup_stability(def_id) {
890 self.fully_stable &= stab.level.is_stable();
893 intravisit::walk_path(self, path)
896 fn visit_trait_ref(&mut self, t: &'tcx TraitRef<'tcx>) {
897 if let Res::Def(DefKind::Trait, trait_did) = t.path.res {
898 if let Some(stab) = self.tcx.lookup_stability(trait_did) {
899 self.fully_stable &= stab.level.is_stable();
902 intravisit::walk_trait_ref(self, t)
905 fn visit_ty(&mut self, t: &'tcx Ty<'tcx>) {
906 if let TyKind::Never = t.kind {
907 self.fully_stable = false;
909 intravisit::walk_ty(self, t)
913 /// Given the list of enabled features that were not language features (i.e., that
914 /// were expected to be library features), and the list of features used from
915 /// libraries, identify activated features that don't exist and error about them.
916 pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {
918 tcx.sess.opts.unstable_opts.force_unstable_if_unmarked || tcx.features().staged_api;
920 let access_levels = &tcx.privacy_access_levels(());
921 let mut missing = MissingStabilityAnnotations { tcx, access_levels };
922 missing.check_missing_stability(CRATE_DEF_ID, tcx.hir().span(CRATE_HIR_ID));
923 tcx.hir().walk_toplevel_module(&mut missing);
924 tcx.hir().visit_all_item_likes_in_crate(&mut missing);
927 let declared_lang_features = &tcx.features().declared_lang_features;
928 let mut lang_features = FxHashSet::default();
929 for &(feature, span, since) in declared_lang_features {
930 if let Some(since) = since {
931 // Warn if the user has enabled an already-stable lang feature.
932 unnecessary_stable_feature_lint(tcx, span, feature, since);
934 if !lang_features.insert(feature) {
935 // Warn if the user enables a lang feature multiple times.
936 duplicate_feature_err(tcx.sess, span, feature);
940 let declared_lib_features = &tcx.features().declared_lib_features;
941 let mut remaining_lib_features = FxIndexMap::default();
942 for (feature, span) in declared_lib_features {
943 if !tcx.sess.opts.unstable_features.is_nightly_build() {
948 "`#![feature]` may not be used on the {} release channel",
949 env!("CFG_RELEASE_CHANNEL")
953 if remaining_lib_features.contains_key(&feature) {
954 // Warn if the user enables a lib feature multiple times.
955 duplicate_feature_err(tcx.sess, *span, *feature);
957 remaining_lib_features.insert(feature, *span);
959 // `stdbuild` has special handling for `libc`, so we need to
960 // recognise the feature when building std.
961 // Likewise, libtest is handled specially, so `test` isn't
962 // available as we'd like it to be.
963 // FIXME: only remove `libc` when `stdbuild` is active.
964 // FIXME: remove special casing for `test`.
965 remaining_lib_features.remove(&sym::libc);
966 remaining_lib_features.remove(&sym::test);
968 /// For each feature in `defined_features`..
970 /// - If it is in `remaining_lib_features` (those features with `#![feature(..)]` attributes in
971 /// the current crate), check if it is stable (or partially stable) and thus an unnecessary
973 /// - If it is in `remaining_implications` (a feature that is referenced by an `implied_by`
974 /// from the current crate), then remove it from the remaining implications.
976 /// Once this function has been invoked for every feature (local crate and all extern crates),
979 /// - If features remain in `remaining_lib_features`, then the user has enabled a feature that
981 /// - If features remain in `remaining_implications`, the `implied_by` refers to a feature that
984 /// By structuring the code in this way: checking the features defined from each crate one at a
985 /// time, less loading from metadata is performed and thus compiler performance is improved.
986 fn check_features<'tcx>(
988 remaining_lib_features: &mut FxIndexMap<&Symbol, Span>,
989 remaining_implications: &mut FxHashMap<Symbol, Symbol>,
990 defined_features: &[(Symbol, Option<Symbol>)],
991 all_implications: &FxHashMap<Symbol, Symbol>,
993 for (feature, since) in defined_features {
994 if let Some(since) = since && let Some(span) = remaining_lib_features.get(&feature) {
995 // Warn if the user has enabled an already-stable lib feature.
996 if let Some(implies) = all_implications.get(&feature) {
997 unnecessary_partially_stable_feature_lint(tcx, *span, *feature, *implies, *since);
999 unnecessary_stable_feature_lint(tcx, *span, *feature, *since);
1003 remaining_lib_features.remove(feature);
1005 // `feature` is the feature doing the implying, but `implied_by` is the feature with
1006 // the attribute that establishes this relationship. `implied_by` is guaranteed to be a
1007 // feature defined in the local crate because `remaining_implications` is only the
1008 // implications from this crate.
1009 remaining_implications.remove(feature);
1011 if remaining_lib_features.is_empty() && remaining_implications.is_empty() {
1017 // All local crate implications need to have the feature that implies it confirmed to exist.
1018 let mut remaining_implications =
1019 tcx.stability_implications(rustc_hir::def_id::LOCAL_CRATE).clone();
1021 // We always collect the lib features declared in the current crate, even if there are
1022 // no unknown features, because the collection also does feature attribute validation.
1023 let local_defined_features = tcx.lib_features(()).to_vec();
1024 if !remaining_lib_features.is_empty() || !remaining_implications.is_empty() {
1025 // Loading the implications of all crates is unavoidable to be able to emit the partial
1026 // stabilization diagnostic, but it can be avoided when there are no
1027 // `remaining_lib_features`.
1028 let mut all_implications = remaining_implications.clone();
1029 for &cnum in tcx.crates(()) {
1030 all_implications.extend(tcx.stability_implications(cnum));
1035 &mut remaining_lib_features,
1036 &mut remaining_implications,
1037 local_defined_features.as_slice(),
1041 for &cnum in tcx.crates(()) {
1042 if remaining_lib_features.is_empty() && remaining_implications.is_empty() {
1047 &mut remaining_lib_features,
1048 &mut remaining_implications,
1049 tcx.defined_lib_features(cnum).to_vec().as_slice(),
1055 for (feature, span) in remaining_lib_features {
1056 struct_span_err!(tcx.sess, span, E0635, "unknown feature `{}`", feature).emit();
1059 for (implied_by, feature) in remaining_implications {
1060 let local_defined_features = tcx.lib_features(());
1061 let span = local_defined_features
1064 .map(|(_, span)| span)
1065 .or_else(|| local_defined_features.unstable.get(&feature))
1066 .expect("feature that implied another does not exist");
1070 format!("feature `{implied_by}` implying `{feature}` does not exist"),
1075 // FIXME(#44232): the `used_features` table no longer exists, so we
1076 // don't lint about unused features. We should re-enable this one day!
1079 fn unnecessary_partially_stable_feature_lint(
1086 tcx.struct_span_lint_hir(lint::builtin::STABLE_FEATURES, hir::CRATE_HIR_ID, span, |lint| {
1087 lint.build(&format!(
1088 "the feature `{feature}` has been partially stabilized since {since} and is succeeded \
1089 by the feature `{implies}`"
1094 "if you are using features which are still unstable, change to using `{implies}`"
1097 Applicability::MaybeIncorrect,
1100 tcx.sess.source_map().span_extend_to_line(span),
1101 "if you are using features which are now stable, remove this line",
1103 Applicability::MaybeIncorrect,
1109 fn unnecessary_stable_feature_lint(tcx: TyCtxt<'_>, span: Span, feature: Symbol, since: Symbol) {
1110 tcx.struct_span_lint_hir(lint::builtin::STABLE_FEATURES, hir::CRATE_HIR_ID, span, |lint| {
1111 lint.build(&format!(
1112 "the feature `{feature}` has been stable since {since} and no longer requires an \
1113 attribute to enable",
1119 fn duplicate_feature_err(sess: &Session, span: Span, feature: Symbol) {
1120 struct_span_err!(sess, span, E0636, "the feature `{}` has already been declared", feature)
1124 fn missing_const_err(session: &Session, fn_sig_span: Span, const_span: Span) {
1125 const ERROR_MSG: &'static str = "attributes `#[rustc_const_unstable]` \
1126 and `#[rustc_const_stable]` require \
1127 the function or method to be `const`";
1130 .struct_span_err(fn_sig_span, ERROR_MSG)
1131 .span_help(fn_sig_span, "make the function or method const")
1132 .span_label(const_span, "attribute specified here")