1 //! A pass that annotates every item and method with its stability level,
2 //! propagating default levels lexically from parent to children ast nodes.
6 self as attr, rust_version_symbol, ConstStability, Stability, StabilityLevel, Unstable,
7 UnstableReason, VERSION_PLACEHOLDER,
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
10 use rustc_errors::{struct_span_err, Applicability};
12 use rustc_hir::def::{DefKind, Res};
13 use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
14 use rustc_hir::hir_id::CRATE_HIR_ID;
15 use rustc_hir::intravisit::{self, Visitor};
16 use rustc_hir::{FieldDef, Item, ItemKind, TraitRef, Ty, TyKind, Variant};
17 use rustc_middle::hir::nested_filter;
18 use rustc_middle::middle::privacy::AccessLevels;
19 use rustc_middle::middle::stability::{AllowUnstable, DeprecationEntry, Index};
20 use rustc_middle::ty::{query::Providers, TyCtxt};
21 use rustc_session::lint;
22 use rustc_session::lint::builtin::{INEFFECTIVE_UNSTABLE_TRAIT_IMPL, USELESS_DEPRECATED};
23 use rustc_session::Session;
24 use rustc_span::symbol::{sym, Symbol};
26 use rustc_target::spec::abi::Abi;
28 use std::cmp::Ordering;
30 use std::mem::replace;
31 use std::num::NonZeroU32;
35 /// Annotation is required if not inherited from unstable parents.
37 /// Annotation is useless, reject it.
39 /// Deprecation annotation is useless, reject it. (Stability attribute is still required.)
40 DeprecationProhibited,
41 /// Annotation itself is useless, but it can be propagated to children.
45 /// Whether to inherit deprecation flags for nested items. In most cases, we do want to inherit
46 /// deprecation, because nested items rarely have individual deprecation attributes, and so
47 /// should be treated as deprecated if their parent is. However, default generic parameters
48 /// have separate deprecation attributes from their parents, so we do not wish to inherit
49 /// deprecation in this case. For example, inheriting deprecation for `T` in `Foo<T>`
50 /// would cause a duplicate warning arising from both `Foo` and `T` being deprecated.
52 enum InheritDeprecation {
57 impl InheritDeprecation {
58 fn yes(&self) -> bool {
59 matches!(self, InheritDeprecation::Yes)
63 /// Whether to inherit const stability flags for nested items. In most cases, we do not want to
64 /// inherit const stability: just because an enclosing `fn` is const-stable does not mean
65 /// all `extern` imports declared in it should be const-stable! However, trait methods
66 /// inherit const stability attributes from their parent and do not have their own.
67 enum InheritConstStability {
72 impl InheritConstStability {
73 fn yes(&self) -> bool {
74 matches!(self, InheritConstStability::Yes)
78 enum InheritStability {
83 impl InheritStability {
84 fn yes(&self) -> bool {
85 matches!(self, InheritStability::Yes)
89 /// A private tree-walker for producing an `Index`.
90 struct Annotator<'a, 'tcx> {
93 parent_stab: Option<Stability>,
94 parent_const_stab: Option<ConstStability>,
95 parent_depr: Option<DeprecationEntry>,
99 impl<'a, 'tcx> Annotator<'a, 'tcx> {
100 /// Determine the stability for a node based on its attributes and inherited stability. The
101 /// stability is recorded in the index and used as the parent. If the node is a function,
102 /// `fn_sig` is its signature.
107 fn_sig: Option<&'tcx hir::FnSig<'tcx>>,
108 kind: AnnotationKind,
109 inherit_deprecation: InheritDeprecation,
110 inherit_const_stability: InheritConstStability,
111 inherit_from_parent: InheritStability,
114 F: FnOnce(&mut Self),
116 let attrs = self.tcx.hir().attrs(self.tcx.hir().local_def_id_to_hir_id(def_id));
117 debug!("annotate(id = {:?}, attrs = {:?})", def_id, attrs);
119 let depr = attr::find_deprecation(&self.tcx.sess, attrs);
120 let mut is_deprecated = false;
121 if let Some((depr, span)) = &depr {
122 is_deprecated = true;
124 if kind == AnnotationKind::Prohibited || kind == AnnotationKind::DeprecationProhibited {
125 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
126 self.tcx.emit_spanned_lint(
130 errors::DeprecatedAnnotationHasNoEffect { span: *span },
134 // `Deprecation` is just two pointers, no need to intern it
135 let depr_entry = DeprecationEntry::local(*depr, def_id);
136 self.index.depr_map.insert(def_id, depr_entry);
137 } else if let Some(parent_depr) = self.parent_depr {
138 if inherit_deprecation.yes() {
139 is_deprecated = true;
140 info!("tagging child {:?} as deprecated from parent", def_id);
141 self.index.depr_map.insert(def_id, parent_depr);
145 if !self.tcx.features().staged_api {
146 // Propagate unstability. This can happen even for non-staged-api crates in case
147 // -Zforce-unstable-if-unmarked is set.
148 if let Some(stab) = self.parent_stab {
149 if inherit_deprecation.yes() && stab.is_unstable() {
150 self.index.stab_map.insert(def_id, stab);
154 self.recurse_with_stability_attrs(
155 depr.map(|(d, _)| DeprecationEntry::local(d, def_id)),
163 let (stab, const_stab, body_stab) = attr::find_stability(&self.tcx.sess, attrs, item_sp);
164 let mut const_span = None;
166 let const_stab = const_stab.map(|(const_stab, const_span_node)| {
167 self.index.const_stab_map.insert(def_id, const_stab);
168 const_span = Some(const_span_node);
172 // If the current node is a function, has const stability attributes and if it doesn not have an intrinsic ABI,
173 // check if the function/method is const or the parent impl block is const
174 if let (Some(const_span), Some(fn_sig)) = (const_span, fn_sig) {
175 if fn_sig.header.abi != Abi::RustIntrinsic
176 && fn_sig.header.abi != Abi::PlatformIntrinsic
177 && !fn_sig.header.is_const()
179 if !self.in_trait_impl
180 || (self.in_trait_impl && !self.tcx.is_const_fn_raw(def_id.to_def_id()))
182 missing_const_err(&self.tcx.sess, fn_sig.span, const_span);
187 // `impl const Trait for Type` items forward their const stability to their
188 // immediate children.
189 if const_stab.is_none() {
190 debug!("annotate: const_stab not found, parent = {:?}", self.parent_const_stab);
191 if let Some(parent) = self.parent_const_stab {
192 if parent.is_const_unstable() {
193 self.index.const_stab_map.insert(def_id, parent);
198 if let Some((rustc_attr::Deprecation { is_since_rustc_version: true, .. }, span)) = &depr {
204 "deprecated attribute must be paired with \
205 either stable or unstable attribute"
211 if let Some((body_stab, _span)) = body_stab {
212 // FIXME: check that this item can have body stability
214 self.index.default_body_stab_map.insert(def_id, body_stab);
215 debug!(?self.index.default_body_stab_map);
218 let stab = stab.map(|(stab, span)| {
219 // Error if prohibited, or can't inherit anything from a container.
220 if kind == AnnotationKind::Prohibited
221 || (kind == AnnotationKind::Container && stab.level.is_stable() && is_deprecated)
223 self.tcx.sess.struct_span_err(span,"this stability annotation is useless")
224 .span_label(span, "useless stability annotation")
225 .span_label(item_sp, "the stability attribute annotates this item")
229 debug!("annotate: found {:?}", stab);
231 // Check if deprecated_since < stable_since. If it is,
232 // this is *almost surely* an accident.
233 if let (&Some(dep_since), &attr::Stable { since: stab_since, .. }) =
234 (&depr.as_ref().and_then(|(d, _)| d.since), &stab.level)
236 // Explicit version of iter::order::lt to handle parse errors properly
237 for (dep_v, stab_v) in
238 iter::zip(dep_since.as_str().split('.'), stab_since.as_str().split('.'))
240 match stab_v.parse::<u64>() {
242 self.tcx.sess.struct_span_err(span, "invalid stability version found")
243 .span_label(span, "invalid stability version")
244 .span_label(item_sp, "the stability attribute annotates this item")
248 Ok(stab_vp) => match dep_v.parse::<u64>() {
249 Ok(dep_vp) => match dep_vp.cmp(&stab_vp) {
251 self.tcx.sess.struct_span_err(span, "an API can't be stabilized after it is deprecated")
252 .span_label(span, "invalid version")
253 .span_label(item_sp, "the stability attribute annotates this item")
257 Ordering::Equal => continue,
258 Ordering::Greater => break,
262 self.tcx.sess.struct_span_err(span, "invalid deprecation version found")
263 .span_label(span, "invalid deprecation version")
264 .span_label(item_sp, "the stability attribute annotates this item")
274 if let Stability { level: Unstable { implied_by: Some(implied_by), .. }, feature } = stab {
275 self.index.implications.insert(implied_by, feature);
278 self.index.stab_map.insert(def_id, stab);
283 debug!("annotate: stab not found, parent = {:?}", self.parent_stab);
284 if let Some(stab) = self.parent_stab {
285 if inherit_deprecation.yes() && stab.is_unstable() || inherit_from_parent.yes() {
286 self.index.stab_map.insert(def_id, stab);
291 self.recurse_with_stability_attrs(
292 depr.map(|(d, _)| DeprecationEntry::local(d, def_id)),
294 if inherit_const_stability.yes() { const_stab } else { None },
299 fn recurse_with_stability_attrs(
301 depr: Option<DeprecationEntry>,
302 stab: Option<Stability>,
303 const_stab: Option<ConstStability>,
304 f: impl FnOnce(&mut Self),
306 // These will be `Some` if this item changes the corresponding stability attribute.
307 let mut replaced_parent_depr = None;
308 let mut replaced_parent_stab = None;
309 let mut replaced_parent_const_stab = None;
311 if let Some(depr) = depr {
312 replaced_parent_depr = Some(replace(&mut self.parent_depr, Some(depr)));
314 if let Some(stab) = stab {
315 replaced_parent_stab = Some(replace(&mut self.parent_stab, Some(stab)));
317 if let Some(const_stab) = const_stab {
318 replaced_parent_const_stab =
319 Some(replace(&mut self.parent_const_stab, Some(const_stab)));
324 if let Some(orig_parent_depr) = replaced_parent_depr {
325 self.parent_depr = orig_parent_depr;
327 if let Some(orig_parent_stab) = replaced_parent_stab {
328 self.parent_stab = orig_parent_stab;
330 if let Some(orig_parent_const_stab) = replaced_parent_const_stab {
331 self.parent_const_stab = orig_parent_const_stab;
336 impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
337 /// Because stability levels are scoped lexically, we want to walk
338 /// nested items in the context of the outer item, so enable
340 type NestedFilter = nested_filter::All;
342 fn nested_visit_map(&mut self) -> Self::Map {
346 fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
347 let orig_in_trait_impl = self.in_trait_impl;
348 let mut kind = AnnotationKind::Required;
349 let mut const_stab_inherit = InheritConstStability::No;
350 let mut fn_sig = None;
353 // Inherent impls and foreign modules serve only as containers for other items,
354 // they don't have their own stability. They still can be annotated as unstable
355 // and propagate this instability to children, but this annotation is completely
356 // optional. They inherit stability from their parents when unannotated.
357 hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
358 | hir::ItemKind::ForeignMod { .. } => {
359 self.in_trait_impl = false;
360 kind = AnnotationKind::Container;
362 hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => {
363 self.in_trait_impl = true;
364 kind = AnnotationKind::DeprecationProhibited;
365 const_stab_inherit = InheritConstStability::Yes;
367 hir::ItemKind::Struct(ref sd, _) => {
368 if let Some(ctor_hir_id) = sd.ctor_hir_id() {
370 self.tcx.hir().local_def_id(ctor_hir_id),
373 AnnotationKind::Required,
374 InheritDeprecation::Yes,
375 InheritConstStability::No,
376 InheritStability::Yes,
381 hir::ItemKind::Fn(ref item_fn_sig, _, _) => {
382 fn_sig = Some(item_fn_sig);
392 InheritDeprecation::Yes,
394 InheritStability::No,
395 |v| intravisit::walk_item(v, i),
397 self.in_trait_impl = orig_in_trait_impl;
400 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
401 let fn_sig = match ti.kind {
402 hir::TraitItemKind::Fn(ref fn_sig, _) => Some(fn_sig),
410 AnnotationKind::Required,
411 InheritDeprecation::Yes,
412 InheritConstStability::No,
413 InheritStability::No,
415 intravisit::walk_trait_item(v, ti);
420 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
422 if self.in_trait_impl { AnnotationKind::Prohibited } else { AnnotationKind::Required };
424 let fn_sig = match ii.kind {
425 hir::ImplItemKind::Fn(ref fn_sig, _) => Some(fn_sig),
434 InheritDeprecation::Yes,
435 InheritConstStability::No,
436 InheritStability::No,
438 intravisit::walk_impl_item(v, ii);
443 fn visit_variant(&mut self, var: &'tcx Variant<'tcx>) {
445 self.tcx.hir().local_def_id(var.id),
448 AnnotationKind::Required,
449 InheritDeprecation::Yes,
450 InheritConstStability::No,
451 InheritStability::Yes,
453 if let Some(ctor_hir_id) = var.data.ctor_hir_id() {
455 v.tcx.hir().local_def_id(ctor_hir_id),
458 AnnotationKind::Required,
459 InheritDeprecation::Yes,
460 InheritConstStability::No,
461 InheritStability::Yes,
466 intravisit::walk_variant(v, var)
471 fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
473 self.tcx.hir().local_def_id(s.hir_id),
476 AnnotationKind::Required,
477 InheritDeprecation::Yes,
478 InheritConstStability::No,
479 InheritStability::Yes,
481 intravisit::walk_field_def(v, s);
486 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
491 AnnotationKind::Required,
492 InheritDeprecation::Yes,
493 InheritConstStability::No,
494 InheritStability::No,
496 intravisit::walk_foreign_item(v, i);
501 fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
502 let kind = match &p.kind {
503 // Allow stability attributes on default generic arguments.
504 hir::GenericParamKind::Type { default: Some(_), .. }
505 | hir::GenericParamKind::Const { default: Some(_), .. } => AnnotationKind::Container,
506 _ => AnnotationKind::Prohibited,
510 self.tcx.hir().local_def_id(p.hir_id),
514 InheritDeprecation::No,
515 InheritConstStability::No,
516 InheritStability::No,
518 intravisit::walk_generic_param(v, p);
524 struct MissingStabilityAnnotations<'tcx> {
526 access_levels: &'tcx AccessLevels,
529 impl<'tcx> MissingStabilityAnnotations<'tcx> {
530 fn check_missing_stability(&self, def_id: LocalDefId, span: Span) {
531 let stab = self.tcx.stability().local_stability(def_id);
532 if !self.tcx.sess.opts.test && stab.is_none() && self.access_levels.is_reachable(def_id) {
533 let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
534 self.tcx.sess.span_err(span, &format!("{} has missing stability attribute", descr));
538 fn check_missing_const_stability(&self, def_id: LocalDefId, span: Span) {
539 if !self.tcx.features().staged_api {
543 let is_const = self.tcx.is_const_fn(def_id.to_def_id())
544 || self.tcx.is_const_trait_impl_raw(def_id.to_def_id());
547 .lookup_stability(def_id)
548 .map_or(false, |stability| stability.level.is_stable());
549 let missing_const_stability_attribute = self.tcx.lookup_const_stability(def_id).is_none();
550 let is_reachable = self.access_levels.is_reachable(def_id);
552 if is_const && is_stable && missing_const_stability_attribute && is_reachable {
553 let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
554 self.tcx.sess.span_err(span, &format!("{descr} has missing const stability attribute"));
559 impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> {
560 type NestedFilter = nested_filter::OnlyBodies;
562 fn nested_visit_map(&mut self) -> Self::Map {
566 fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
567 // Inherent impls and foreign modules serve only as containers for other items,
568 // they don't have their own stability. They still can be annotated as unstable
569 // and propagate this instability to children, but this annotation is completely
570 // optional. They inherit stability from their parents when unannotated.
573 hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
574 | hir::ItemKind::ForeignMod { .. }
576 self.check_missing_stability(i.def_id.def_id, i.span);
579 // Ensure stable `const fn` have a const stability attribute.
580 self.check_missing_const_stability(i.def_id.def_id, i.span);
582 intravisit::walk_item(self, i)
585 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
586 self.check_missing_stability(ti.def_id.def_id, ti.span);
587 intravisit::walk_trait_item(self, ti);
590 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
591 let impl_def_id = self.tcx.hir().get_parent_item(ii.hir_id());
592 if self.tcx.impl_trait_ref(impl_def_id).is_none() {
593 self.check_missing_stability(ii.def_id.def_id, ii.span);
594 self.check_missing_const_stability(ii.def_id.def_id, ii.span);
596 intravisit::walk_impl_item(self, ii);
599 fn visit_variant(&mut self, var: &'tcx Variant<'tcx>) {
600 self.check_missing_stability(self.tcx.hir().local_def_id(var.id), var.span);
601 if let Some(ctor_hir_id) = var.data.ctor_hir_id() {
602 self.check_missing_stability(self.tcx.hir().local_def_id(ctor_hir_id), var.span);
604 intravisit::walk_variant(self, var);
607 fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
608 self.check_missing_stability(self.tcx.hir().local_def_id(s.hir_id), s.span);
609 intravisit::walk_field_def(self, s);
612 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
613 self.check_missing_stability(i.def_id.def_id, i.span);
614 intravisit::walk_foreign_item(self, i);
616 // Note that we don't need to `check_missing_stability` for default generic parameters,
617 // as we assume that any default generic parameters without attributes are automatically
618 // stable (assuming they have not inherited instability from their parent).
621 fn stability_index(tcx: TyCtxt<'_>, (): ()) -> Index {
622 let mut index = Index {
623 stab_map: Default::default(),
624 const_stab_map: Default::default(),
625 default_body_stab_map: Default::default(),
626 depr_map: Default::default(),
627 implications: Default::default(),
631 let mut annotator = Annotator {
635 parent_const_stab: None,
637 in_trait_impl: false,
640 // If the `-Z force-unstable-if-unmarked` flag is passed then we provide
641 // a parent stability annotation which indicates that this is private
642 // with the `rustc_private` feature. This is intended for use when
643 // compiling `librustc_*` crates themselves so we can leverage crates.io
644 // while maintaining the invariant that all sysroot crates are unstable
645 // by default and are unable to be used.
646 if tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
647 let stability = Stability {
648 level: attr::StabilityLevel::Unstable {
649 reason: UnstableReason::Default,
650 issue: NonZeroU32::new(27812),
654 feature: sym::rustc_private,
656 annotator.parent_stab = Some(stability);
661 tcx.hir().span(CRATE_HIR_ID),
663 AnnotationKind::Required,
664 InheritDeprecation::Yes,
665 InheritConstStability::No,
666 InheritStability::No,
667 |v| tcx.hir().walk_toplevel_module(v),
673 /// Cross-references the feature names of unstable APIs with enabled
674 /// features and possibly prints errors.
675 fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
676 tcx.hir().visit_item_likes_in_module(module_def_id, &mut Checker { tcx });
679 pub(crate) fn provide(providers: &mut Providers) {
680 *providers = Providers {
681 check_mod_unstable_api_usage,
683 stability_implications: |tcx, _| tcx.stability().implications.clone(),
684 lookup_stability: |tcx, id| tcx.stability().local_stability(id.expect_local()),
685 lookup_const_stability: |tcx, id| tcx.stability().local_const_stability(id.expect_local()),
686 lookup_default_body_stability: |tcx, id| {
687 tcx.stability().local_default_body_stability(id.expect_local())
689 lookup_deprecation_entry: |tcx, id| {
690 tcx.stability().local_deprecation_entry(id.expect_local())
696 struct Checker<'tcx> {
700 impl<'tcx> Visitor<'tcx> for Checker<'tcx> {
701 type NestedFilter = nested_filter::OnlyBodies;
703 /// Because stability levels are scoped lexically, we want to walk
704 /// nested items in the context of the outer item, so enable
706 fn nested_visit_map(&mut self) -> Self::Map {
710 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
712 hir::ItemKind::ExternCrate(_) => {
713 // compiler-generated `extern crate` items have a dummy span.
714 // `std` is still checked for the `restricted-std` feature.
715 if item.span.is_dummy() && item.ident.name != sym::std {
719 let Some(cnum) = self.tcx.extern_mod_stmt_cnum(item.def_id.def_id) else {
722 let def_id = cnum.as_def_id();
723 self.tcx.check_stability(def_id, Some(item.hir_id()), item.span, None);
726 // For implementations of traits, check the stability of each item
727 // individually as it's possible to have a stable trait with unstable
729 hir::ItemKind::Impl(hir::Impl {
730 of_trait: Some(ref t),
736 let features = self.tcx.features();
737 if features.staged_api {
738 let attrs = self.tcx.hir().attrs(item.hir_id());
739 let (stab, const_stab, _) =
740 attr::find_stability(&self.tcx.sess, attrs, item.span);
742 // If this impl block has an #[unstable] attribute, give an
743 // error if all involved types and traits are stable, because
744 // it will have no effect.
745 // See: https://github.com/rust-lang/rust/issues/55436
746 if let Some((Stability { level: attr::Unstable { .. }, .. }, span)) = stab {
747 let mut c = CheckTraitImplStable { tcx: self.tcx, fully_stable: true };
749 c.visit_trait_ref(t);
751 self.tcx.struct_span_lint_hir(
752 INEFFECTIVE_UNSTABLE_TRAIT_IMPL,
756 .build("an `#[unstable]` annotation here has no effect")
757 .note("see issue #55436 <https://github.com/rust-lang/rust/issues/55436> for more information")
763 // `#![feature(const_trait_impl)]` is unstable, so any impl declared stable
764 // needs to have an error emitted.
765 if features.const_trait_impl
766 && *constness == hir::Constness::Const
767 && const_stab.map_or(false, |(stab, _)| stab.is_const_stable())
771 .struct_span_err(item.span, "trait implementations cannot be const stable yet")
772 .note("see issue #67792 <https://github.com/rust-lang/rust/issues/67792> for more information")
777 for impl_item_ref in *items {
778 let impl_item = self.tcx.associated_item(impl_item_ref.id.def_id);
780 if let Some(def_id) = impl_item.trait_item_def_id {
781 // Pass `None` to skip deprecation warnings.
782 self.tcx.check_stability(def_id, None, impl_item_ref.span, None);
789 intravisit::walk_item(self, item);
792 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, id: hir::HirId) {
793 if let Some(def_id) = path.res.opt_def_id() {
794 let method_span = path.segments.last().map(|s| s.ident.span);
795 let item_is_allowed = self.tcx.check_stability_allow_unstable(
800 if is_unstable_reexport(self.tcx, id) {
807 let is_allowed_through_unstable_modules = |def_id| {
809 .lookup_stability(def_id)
810 .map(|stab| match stab.level {
811 StabilityLevel::Stable { allowed_through_unstable_modules, .. } => {
812 allowed_through_unstable_modules
819 if item_is_allowed && !is_allowed_through_unstable_modules(def_id) {
820 // Check parent modules stability as well if the item the path refers to is itself
821 // stable. We only emit warnings for unstable path segments if the item is stable
822 // or allowed because stability is often inherited, so the most common case is that
823 // both the segments and the item are unstable behind the same feature flag.
825 // We check here rather than in `visit_path_segment` to prevent visiting the last
826 // path segment twice
828 // We include special cases via #[rustc_allowed_through_unstable_modules] for items
829 // that were accidentally stabilized through unstable paths before this check was
830 // added, such as `core::intrinsics::transmute`
831 let parents = path.segments.iter().rev().skip(1);
832 for path_segment in parents {
833 if let Some(def_id) = path_segment.res.opt_def_id() {
834 // use `None` for id to prevent deprecation check
835 self.tcx.check_stability_allow_unstable(
840 if is_unstable_reexport(self.tcx, id) {
851 intravisit::walk_path(self, path)
855 /// Check whether a path is a `use` item that has been marked as unstable.
857 /// See issue #94972 for details on why this is a special case
858 fn is_unstable_reexport<'tcx>(tcx: TyCtxt<'tcx>, id: hir::HirId) -> bool {
859 // Get the LocalDefId so we can lookup the item to check the kind.
860 let Some(def_id) = tcx.hir().opt_local_def_id(id) else { return false; };
862 let Some(stab) = tcx.stability().local_stability(def_id) else {
866 if stab.level.is_stable() {
867 // The re-export is not marked as unstable, don't override
871 // If this is a path that isn't a use, we don't need to do anything special
872 if !matches!(tcx.hir().expect_item(def_id).kind, ItemKind::Use(..)) {
879 struct CheckTraitImplStable<'tcx> {
884 impl<'tcx> Visitor<'tcx> for CheckTraitImplStable<'tcx> {
885 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _id: hir::HirId) {
886 if let Some(def_id) = path.res.opt_def_id() {
887 if let Some(stab) = self.tcx.lookup_stability(def_id) {
888 self.fully_stable &= stab.level.is_stable();
891 intravisit::walk_path(self, path)
894 fn visit_trait_ref(&mut self, t: &'tcx TraitRef<'tcx>) {
895 if let Res::Def(DefKind::Trait, trait_did) = t.path.res {
896 if let Some(stab) = self.tcx.lookup_stability(trait_did) {
897 self.fully_stable &= stab.level.is_stable();
900 intravisit::walk_trait_ref(self, t)
903 fn visit_ty(&mut self, t: &'tcx Ty<'tcx>) {
904 if let TyKind::Never = t.kind {
905 self.fully_stable = false;
907 intravisit::walk_ty(self, t)
911 /// Given the list of enabled features that were not language features (i.e., that
912 /// were expected to be library features), and the list of features used from
913 /// libraries, identify activated features that don't exist and error about them.
914 pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {
916 tcx.sess.opts.unstable_opts.force_unstable_if_unmarked || tcx.features().staged_api;
918 let access_levels = &tcx.privacy_access_levels(());
919 let mut missing = MissingStabilityAnnotations { tcx, access_levels };
920 missing.check_missing_stability(CRATE_DEF_ID, tcx.hir().span(CRATE_HIR_ID));
921 tcx.hir().walk_toplevel_module(&mut missing);
922 tcx.hir().visit_all_item_likes_in_crate(&mut missing);
925 let declared_lang_features = &tcx.features().declared_lang_features;
926 let mut lang_features = FxHashSet::default();
927 for &(feature, span, since) in declared_lang_features {
928 if let Some(since) = since {
929 // Warn if the user has enabled an already-stable lang feature.
930 unnecessary_stable_feature_lint(tcx, span, feature, since);
932 if !lang_features.insert(feature) {
933 // Warn if the user enables a lang feature multiple times.
934 duplicate_feature_err(tcx.sess, span, feature);
938 let declared_lib_features = &tcx.features().declared_lib_features;
939 let mut remaining_lib_features = FxIndexMap::default();
940 for (feature, span) in declared_lib_features {
941 if !tcx.sess.opts.unstable_features.is_nightly_build() {
946 "`#![feature]` may not be used on the {} release channel",
947 env!("CFG_RELEASE_CHANNEL")
951 if remaining_lib_features.contains_key(&feature) {
952 // Warn if the user enables a lib feature multiple times.
953 duplicate_feature_err(tcx.sess, *span, *feature);
955 remaining_lib_features.insert(feature, *span);
957 // `stdbuild` has special handling for `libc`, so we need to
958 // recognise the feature when building std.
959 // Likewise, libtest is handled specially, so `test` isn't
960 // available as we'd like it to be.
961 // FIXME: only remove `libc` when `stdbuild` is active.
962 // FIXME: remove special casing for `test`.
963 remaining_lib_features.remove(&sym::libc);
964 remaining_lib_features.remove(&sym::test);
966 /// For each feature in `defined_features`..
968 /// - If it is in `remaining_lib_features` (those features with `#![feature(..)]` attributes in
969 /// the current crate), check if it is stable (or partially stable) and thus an unnecessary
971 /// - If it is in `remaining_implications` (a feature that is referenced by an `implied_by`
972 /// from the current crate), then remove it from the remaining implications.
974 /// Once this function has been invoked for every feature (local crate and all extern crates),
977 /// - If features remain in `remaining_lib_features`, then the user has enabled a feature that
979 /// - If features remain in `remaining_implications`, the `implied_by` refers to a feature that
982 /// By structuring the code in this way: checking the features defined from each crate one at a
983 /// time, less loading from metadata is performed and thus compiler performance is improved.
984 fn check_features<'tcx>(
986 remaining_lib_features: &mut FxIndexMap<&Symbol, Span>,
987 remaining_implications: &mut FxHashMap<Symbol, Symbol>,
988 defined_features: &[(Symbol, Option<Symbol>)],
989 all_implications: &FxHashMap<Symbol, Symbol>,
991 for (feature, since) in defined_features {
992 if let Some(since) = since && let Some(span) = remaining_lib_features.get(&feature) {
993 // Warn if the user has enabled an already-stable lib feature.
994 if let Some(implies) = all_implications.get(&feature) {
995 unnecessary_partially_stable_feature_lint(tcx, *span, *feature, *implies, *since);
997 unnecessary_stable_feature_lint(tcx, *span, *feature, *since);
1001 remaining_lib_features.remove(feature);
1003 // `feature` is the feature doing the implying, but `implied_by` is the feature with
1004 // the attribute that establishes this relationship. `implied_by` is guaranteed to be a
1005 // feature defined in the local crate because `remaining_implications` is only the
1006 // implications from this crate.
1007 remaining_implications.remove(feature);
1009 if remaining_lib_features.is_empty() && remaining_implications.is_empty() {
1015 // All local crate implications need to have the feature that implies it confirmed to exist.
1016 let mut remaining_implications =
1017 tcx.stability_implications(rustc_hir::def_id::LOCAL_CRATE).clone();
1019 // We always collect the lib features declared in the current crate, even if there are
1020 // no unknown features, because the collection also does feature attribute validation.
1021 let local_defined_features = tcx.lib_features(()).to_vec();
1022 if !remaining_lib_features.is_empty() || !remaining_implications.is_empty() {
1023 // Loading the implications of all crates is unavoidable to be able to emit the partial
1024 // stabilization diagnostic, but it can be avoided when there are no
1025 // `remaining_lib_features`.
1026 let mut all_implications = remaining_implications.clone();
1027 for &cnum in tcx.crates(()) {
1028 all_implications.extend(tcx.stability_implications(cnum));
1033 &mut remaining_lib_features,
1034 &mut remaining_implications,
1035 local_defined_features.as_slice(),
1039 for &cnum in tcx.crates(()) {
1040 if remaining_lib_features.is_empty() && remaining_implications.is_empty() {
1045 &mut remaining_lib_features,
1046 &mut remaining_implications,
1047 tcx.defined_lib_features(cnum).to_vec().as_slice(),
1053 for (feature, span) in remaining_lib_features {
1054 struct_span_err!(tcx.sess, span, E0635, "unknown feature `{}`", feature).emit();
1057 for (implied_by, feature) in remaining_implications {
1058 let local_defined_features = tcx.lib_features(());
1059 let span = local_defined_features
1062 .map(|(_, span)| span)
1063 .or_else(|| local_defined_features.unstable.get(&feature))
1064 .expect("feature that implied another does not exist");
1068 format!("feature `{implied_by}` implying `{feature}` does not exist"),
1073 // FIXME(#44232): the `used_features` table no longer exists, so we
1074 // don't lint about unused features. We should re-enable this one day!
1077 fn unnecessary_partially_stable_feature_lint(
1084 tcx.struct_span_lint_hir(lint::builtin::STABLE_FEATURES, hir::CRATE_HIR_ID, span, |lint| {
1085 lint.build(&format!(
1086 "the feature `{feature}` has been partially stabilized since {since} and is succeeded \
1087 by the feature `{implies}`"
1092 "if you are using features which are still unstable, change to using `{implies}`"
1095 Applicability::MaybeIncorrect,
1098 tcx.sess.source_map().span_extend_to_line(span),
1099 "if you are using features which are now stable, remove this line",
1101 Applicability::MaybeIncorrect,
1107 fn unnecessary_stable_feature_lint(
1113 if since.as_str() == VERSION_PLACEHOLDER {
1114 since = rust_version_symbol();
1116 tcx.struct_span_lint_hir(lint::builtin::STABLE_FEATURES, hir::CRATE_HIR_ID, span, |lint| {
1117 lint.build(&format!(
1118 "the feature `{feature}` has been stable since {since} and no longer requires an \
1119 attribute to enable",
1125 fn duplicate_feature_err(sess: &Session, span: Span, feature: Symbol) {
1126 struct_span_err!(sess, span, E0636, "the feature `{}` has already been declared", feature)
1130 fn missing_const_err(session: &Session, fn_sig_span: Span, const_span: Span) {
1131 const ERROR_MSG: &'static str = "attributes `#[rustc_const_unstable]` \
1132 and `#[rustc_const_stable]` require \
1133 the function or method to be `const`";
1136 .struct_span_err(fn_sig_span, ERROR_MSG)
1137 .span_help(fn_sig_span, "make the function or method const")
1138 .span_label(const_span, "attribute specified here")