1 //! A pass that annotates every item and method with its stability level,
2 //! propagating default levels lexically from parent to children ast nodes.
4 use rustc_attr::{self as attr, ConstStability, Stability};
5 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
6 use rustc_errors::struct_span_err;
8 use rustc_hir::def::{DefKind, Res};
9 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX};
10 use rustc_hir::hir_id::CRATE_HIR_ID;
11 use rustc_hir::intravisit::{self, Visitor};
12 use rustc_hir::{FieldDef, Generics, HirId, Item, TraitRef, Ty, TyKind, Variant};
13 use rustc_middle::hir::nested_filter;
14 use rustc_middle::middle::privacy::AccessLevels;
15 use rustc_middle::middle::stability::{DeprecationEntry, Index};
16 use rustc_middle::ty::{self, query::Providers, TyCtxt};
17 use rustc_session::lint;
18 use rustc_session::lint::builtin::{INEFFECTIVE_UNSTABLE_TRAIT_IMPL, USELESS_DEPRECATED};
19 use rustc_session::parse::feature_err;
20 use rustc_session::Session;
21 use rustc_span::symbol::{sym, Symbol};
22 use rustc_span::{Span, DUMMY_SP};
23 use rustc_target::spec::abi::Abi;
25 use std::cmp::Ordering;
27 use std::mem::replace;
28 use std::num::NonZeroU32;
32 // Annotation is required if not inherited from unstable parents
34 // Annotation is useless, reject it
36 // Deprecation annotation is useless, reject it. (Stability attribute is still required.)
37 DeprecationProhibited,
38 // Annotation itself is useless, but it can be propagated to children
42 /// Whether to inherit deprecation flags for nested items. In most cases, we do want to inherit
43 /// deprecation, because nested items rarely have individual deprecation attributes, and so
44 /// should be treated as deprecated if their parent is. However, default generic parameters
45 /// have separate deprecation attributes from their parents, so we do not wish to inherit
46 /// deprecation in this case. For example, inheriting deprecation for `T` in `Foo<T>`
47 /// would cause a duplicate warning arising from both `Foo` and `T` being deprecated.
49 enum InheritDeprecation {
54 impl InheritDeprecation {
55 fn yes(&self) -> bool {
56 matches!(self, InheritDeprecation::Yes)
60 /// Whether to inherit const stability flags for nested items. In most cases, we do not want to
61 /// inherit const stability: just because an enclosing `fn` is const-stable does not mean
62 /// all `extern` imports declared in it should be const-stable! However, trait methods
63 /// inherit const stability attributes from their parent and do not have their own.
64 enum InheritConstStability {
69 impl InheritConstStability {
70 fn yes(&self) -> bool {
71 matches!(self, InheritConstStability::Yes)
75 enum InheritStability {
80 impl InheritStability {
81 fn yes(&self) -> bool {
82 matches!(self, InheritStability::Yes)
86 // A private tree-walker for producing an Index.
87 struct Annotator<'a, 'tcx> {
90 parent_stab: Option<Stability>,
91 parent_const_stab: Option<ConstStability>,
92 parent_depr: Option<DeprecationEntry>,
96 impl<'a, 'tcx> Annotator<'a, 'tcx> {
97 // Determine the stability for a node based on its attributes and inherited
98 // stability. The stability is recorded in the index and used as the parent.
99 // If the node is a function, `fn_sig` is its signature
104 fn_sig: Option<&'tcx hir::FnSig<'tcx>>,
105 kind: AnnotationKind,
106 inherit_deprecation: InheritDeprecation,
107 inherit_const_stability: InheritConstStability,
108 inherit_from_parent: InheritStability,
111 F: FnOnce(&mut Self),
113 let attrs = self.tcx.get_attrs(def_id.to_def_id());
114 debug!("annotate(id = {:?}, attrs = {:?})", def_id, attrs);
116 let depr = attr::find_deprecation(&self.tcx.sess, attrs);
117 let mut is_deprecated = false;
118 if let Some((depr, span)) = &depr {
119 is_deprecated = true;
121 if kind == AnnotationKind::Prohibited || kind == AnnotationKind::DeprecationProhibited {
122 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
123 self.tcx.struct_span_lint_hir(USELESS_DEPRECATED, hir_id, *span, |lint| {
124 lint.build("this `#[deprecated]` annotation has no effect")
125 .span_suggestion_short(
127 "remove the unnecessary deprecation attribute",
129 rustc_errors::Applicability::MachineApplicable,
135 // `Deprecation` is just two pointers, no need to intern it
136 let depr_entry = DeprecationEntry::local(depr.clone(), def_id);
137 self.index.depr_map.insert(def_id, depr_entry);
138 } else if let Some(parent_depr) = self.parent_depr.clone() {
139 if inherit_deprecation.yes() {
140 is_deprecated = true;
141 info!("tagging child {:?} as deprecated from parent", def_id);
142 self.index.depr_map.insert(def_id, parent_depr);
146 if !self.tcx.features().staged_api {
147 // Propagate unstability. This can happen even for non-staged-api crates in case
148 // -Zforce-unstable-if-unmarked is set.
149 if let Some(stab) = self.parent_stab {
150 if inherit_deprecation.yes() && stab.level.is_unstable() {
151 self.index.stab_map.insert(def_id, stab);
155 self.recurse_with_stability_attrs(
156 depr.map(|(d, _)| DeprecationEntry::local(d, def_id)),
164 let (stab, const_stab) = attr::find_stability(&self.tcx.sess, attrs, item_sp);
165 let mut const_span = None;
167 let const_stab = const_stab.map(|(const_stab, const_span_node)| {
168 self.index.const_stab_map.insert(def_id, const_stab);
169 const_span = Some(const_span_node);
173 // If the current node is a function, has const stability attributes and if it doesn not have an intrinsic ABI,
174 // check if the function/method is const or the parent impl block is const
175 if let (Some(const_span), Some(fn_sig)) = (const_span, fn_sig) {
176 if fn_sig.header.abi != Abi::RustIntrinsic
177 && fn_sig.header.abi != Abi::PlatformIntrinsic
178 && !fn_sig.header.is_const()
180 if !self.in_trait_impl
181 || (self.in_trait_impl && !self.tcx.is_const_fn_raw(def_id.to_def_id()))
183 missing_const_err(&self.tcx.sess, fn_sig.span, const_span);
188 // `impl const Trait for Type` items forward their const stability to their
189 // immediate children.
190 if const_stab.is_none() {
191 debug!("annotate: const_stab not found, parent = {:?}", self.parent_const_stab);
192 if let Some(parent) = self.parent_const_stab {
193 if parent.level.is_unstable() {
194 self.index.const_stab_map.insert(def_id, parent);
199 if let Some((rustc_attr::Deprecation { is_since_rustc_version: true, .. }, span)) = &depr {
205 "deprecated attribute must be paired with \
206 either stable or unstable attribute"
212 let stab = stab.map(|(stab, span)| {
213 // Error if prohibited, or can't inherit anything from a container.
214 if kind == AnnotationKind::Prohibited
215 || (kind == AnnotationKind::Container && stab.level.is_stable() && is_deprecated)
217 self.tcx.sess.struct_span_err(span,"this stability annotation is useless")
218 .span_label(span, "useless stability annotation")
219 .span_label(item_sp, "the stability attribute annotates this item")
223 debug!("annotate: found {:?}", stab);
225 // Check if deprecated_since < stable_since. If it is,
226 // this is *almost surely* an accident.
227 if let (&Some(dep_since), &attr::Stable { since: stab_since }) =
228 (&depr.as_ref().and_then(|(d, _)| d.since), &stab.level)
230 // Explicit version of iter::order::lt to handle parse errors properly
231 for (dep_v, stab_v) in
232 iter::zip(dep_since.as_str().split('.'), stab_since.as_str().split('.'))
234 match stab_v.parse::<u64>() {
236 self.tcx.sess.struct_span_err(span, "invalid stability version found")
237 .span_label(span, "invalid stability version")
238 .span_label(item_sp, "the stability attribute annotates this item")
242 Ok(stab_vp) => match dep_v.parse::<u64>() {
243 Ok(dep_vp) => match dep_vp.cmp(&stab_vp) {
245 self.tcx.sess.struct_span_err(span, "an API can't be stabilized after it is deprecated")
246 .span_label(span, "invalid version")
247 .span_label(item_sp, "the stability attribute annotates this item")
251 Ordering::Equal => continue,
252 Ordering::Greater => break,
256 self.tcx.sess.struct_span_err(span, "invalid deprecation version found")
257 .span_label(span, "invalid deprecation version")
258 .span_label(item_sp, "the stability attribute annotates this item")
268 self.index.stab_map.insert(def_id, stab);
273 debug!("annotate: stab not found, parent = {:?}", self.parent_stab);
274 if let Some(stab) = self.parent_stab {
275 if inherit_deprecation.yes() && stab.level.is_unstable()
276 || inherit_from_parent.yes()
278 self.index.stab_map.insert(def_id, stab);
283 self.recurse_with_stability_attrs(
284 depr.map(|(d, _)| DeprecationEntry::local(d, def_id)),
286 if inherit_const_stability.yes() { const_stab } else { None },
291 fn recurse_with_stability_attrs(
293 depr: Option<DeprecationEntry>,
294 stab: Option<Stability>,
295 const_stab: Option<ConstStability>,
296 f: impl FnOnce(&mut Self),
298 // These will be `Some` if this item changes the corresponding stability attribute.
299 let mut replaced_parent_depr = None;
300 let mut replaced_parent_stab = None;
301 let mut replaced_parent_const_stab = None;
303 if let Some(depr) = depr {
304 replaced_parent_depr = Some(replace(&mut self.parent_depr, Some(depr)));
306 if let Some(stab) = stab {
307 replaced_parent_stab = Some(replace(&mut self.parent_stab, Some(stab)));
309 if let Some(const_stab) = const_stab {
310 replaced_parent_const_stab =
311 Some(replace(&mut self.parent_const_stab, Some(const_stab)));
316 if let Some(orig_parent_depr) = replaced_parent_depr {
317 self.parent_depr = orig_parent_depr;
319 if let Some(orig_parent_stab) = replaced_parent_stab {
320 self.parent_stab = orig_parent_stab;
322 if let Some(orig_parent_const_stab) = replaced_parent_const_stab {
323 self.parent_const_stab = orig_parent_const_stab;
328 impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
329 /// Because stability levels are scoped lexically, we want to walk
330 /// nested items in the context of the outer item, so enable
332 type NestedFilter = nested_filter::All;
334 fn nested_visit_map(&mut self) -> Self::Map {
338 fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
339 let orig_in_trait_impl = self.in_trait_impl;
340 let mut kind = AnnotationKind::Required;
341 let mut const_stab_inherit = InheritConstStability::No;
342 let mut fn_sig = None;
345 // Inherent impls and foreign modules serve only as containers for other items,
346 // they don't have their own stability. They still can be annotated as unstable
347 // and propagate this unstability to children, but this annotation is completely
348 // optional. They inherit stability from their parents when unannotated.
349 hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
350 | hir::ItemKind::ForeignMod { .. } => {
351 self.in_trait_impl = false;
352 kind = AnnotationKind::Container;
354 hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => {
355 self.in_trait_impl = true;
356 kind = AnnotationKind::DeprecationProhibited;
357 const_stab_inherit = InheritConstStability::Yes;
359 hir::ItemKind::Struct(ref sd, _) => {
360 if let Some(ctor_hir_id) = sd.ctor_hir_id() {
362 self.tcx.hir().local_def_id(ctor_hir_id),
365 AnnotationKind::Required,
366 InheritDeprecation::Yes,
367 InheritConstStability::No,
368 InheritStability::Yes,
373 hir::ItemKind::Fn(ref item_fn_sig, _, _) => {
374 fn_sig = Some(item_fn_sig);
384 InheritDeprecation::Yes,
386 InheritStability::No,
387 |v| intravisit::walk_item(v, i),
389 self.in_trait_impl = orig_in_trait_impl;
392 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
393 let fn_sig = match ti.kind {
394 hir::TraitItemKind::Fn(ref fn_sig, _) => Some(fn_sig),
402 AnnotationKind::Required,
403 InheritDeprecation::Yes,
404 InheritConstStability::No,
405 InheritStability::No,
407 intravisit::walk_trait_item(v, ti);
412 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
414 if self.in_trait_impl { AnnotationKind::Prohibited } else { AnnotationKind::Required };
416 let fn_sig = match ii.kind {
417 hir::ImplItemKind::Fn(ref fn_sig, _) => Some(fn_sig),
426 InheritDeprecation::Yes,
427 InheritConstStability::No,
428 InheritStability::No,
430 intravisit::walk_impl_item(v, ii);
435 fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) {
437 self.tcx.hir().local_def_id(var.id),
440 AnnotationKind::Required,
441 InheritDeprecation::Yes,
442 InheritConstStability::No,
443 InheritStability::Yes,
445 if let Some(ctor_hir_id) = var.data.ctor_hir_id() {
447 v.tcx.hir().local_def_id(ctor_hir_id),
450 AnnotationKind::Required,
451 InheritDeprecation::Yes,
452 InheritConstStability::No,
453 InheritStability::No,
458 intravisit::walk_variant(v, var, g, item_id)
463 fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
465 self.tcx.hir().local_def_id(s.hir_id),
468 AnnotationKind::Required,
469 InheritDeprecation::Yes,
470 InheritConstStability::No,
471 InheritStability::Yes,
473 intravisit::walk_field_def(v, s);
478 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
483 AnnotationKind::Required,
484 InheritDeprecation::Yes,
485 InheritConstStability::No,
486 InheritStability::No,
488 intravisit::walk_foreign_item(v, i);
493 fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
494 let kind = match &p.kind {
495 // Allow stability attributes on default generic arguments.
496 hir::GenericParamKind::Type { default: Some(_), .. }
497 | hir::GenericParamKind::Const { default: Some(_), .. } => AnnotationKind::Container,
498 _ => AnnotationKind::Prohibited,
502 self.tcx.hir().local_def_id(p.hir_id),
506 InheritDeprecation::No,
507 InheritConstStability::No,
508 InheritStability::No,
510 intravisit::walk_generic_param(v, p);
516 struct MissingStabilityAnnotations<'tcx> {
518 access_levels: &'tcx AccessLevels,
521 impl<'tcx> MissingStabilityAnnotations<'tcx> {
522 fn check_missing_stability(&self, def_id: LocalDefId, span: Span) {
523 let stab = self.tcx.stability().local_stability(def_id);
524 if !self.tcx.sess.opts.test && stab.is_none() && self.access_levels.is_reachable(def_id) {
525 let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
526 self.tcx.sess.span_err(span, &format!("{} has missing stability attribute", descr));
530 fn check_missing_const_stability(&self, def_id: LocalDefId, span: Span) {
531 if !self.tcx.features().staged_api {
535 let is_const = self.tcx.is_const_fn(def_id.to_def_id());
538 .lookup_stability(def_id)
539 .map_or(false, |stability| stability.level.is_stable());
540 let missing_const_stability_attribute = self.tcx.lookup_const_stability(def_id).is_none();
541 let is_reachable = self.access_levels.is_reachable(def_id);
543 if is_const && is_stable && missing_const_stability_attribute && is_reachable {
544 let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
545 self.tcx.sess.span_err(span, &format!("{descr} has missing const stability attribute"));
550 impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> {
551 type NestedFilter = nested_filter::OnlyBodies;
553 fn nested_visit_map(&mut self) -> Self::Map {
557 fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
558 // Inherent impls and foreign modules serve only as containers for other items,
559 // they don't have their own stability. They still can be annotated as unstable
560 // and propagate this unstability to children, but this annotation is completely
561 // optional. They inherit stability from their parents when unannotated.
564 hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
565 | hir::ItemKind::ForeignMod { .. }
567 self.check_missing_stability(i.def_id, i.span);
570 // Ensure stable `const fn` have a const stability attribute.
571 self.check_missing_const_stability(i.def_id, i.span);
573 intravisit::walk_item(self, i)
576 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
577 self.check_missing_stability(ti.def_id, ti.span);
578 intravisit::walk_trait_item(self, ti);
581 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
582 let impl_def_id = self.tcx.hir().get_parent_item(ii.hir_id());
583 if self.tcx.impl_trait_ref(impl_def_id).is_none() {
584 self.check_missing_stability(ii.def_id, ii.span);
585 self.check_missing_const_stability(ii.def_id, ii.span);
587 intravisit::walk_impl_item(self, ii);
590 fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) {
591 self.check_missing_stability(self.tcx.hir().local_def_id(var.id), var.span);
592 intravisit::walk_variant(self, var, g, item_id);
595 fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
596 self.check_missing_stability(self.tcx.hir().local_def_id(s.hir_id), s.span);
597 intravisit::walk_field_def(self, s);
600 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
601 self.check_missing_stability(i.def_id, i.span);
602 intravisit::walk_foreign_item(self, i);
604 // Note that we don't need to `check_missing_stability` for default generic parameters,
605 // as we assume that any default generic parameters without attributes are automatically
606 // stable (assuming they have not inherited instability from their parent).
609 fn stability_index(tcx: TyCtxt<'_>, (): ()) -> Index {
610 let mut index = Index {
611 stab_map: Default::default(),
612 const_stab_map: Default::default(),
613 depr_map: Default::default(),
617 let mut annotator = Annotator {
621 parent_const_stab: None,
623 in_trait_impl: false,
626 // If the `-Z force-unstable-if-unmarked` flag is passed then we provide
627 // a parent stability annotation which indicates that this is private
628 // with the `rustc_private` feature. This is intended for use when
629 // compiling `librustc_*` crates themselves so we can leverage crates.io
630 // while maintaining the invariant that all sysroot crates are unstable
631 // by default and are unable to be used.
632 if tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
633 let reason = "this crate is being loaded from the sysroot, an \
634 unstable location; did you mean to load this crate \
635 from crates.io via `Cargo.toml` instead?";
636 let stability = Stability {
637 level: attr::StabilityLevel::Unstable {
638 reason: Some(Symbol::intern(reason)),
639 issue: NonZeroU32::new(27812),
642 feature: sym::rustc_private,
644 annotator.parent_stab = Some(stability);
649 tcx.hir().span(CRATE_HIR_ID),
651 AnnotationKind::Required,
652 InheritDeprecation::Yes,
653 InheritConstStability::No,
654 InheritStability::No,
655 |v| tcx.hir().walk_toplevel_module(v),
661 /// Cross-references the feature names of unstable APIs with enabled
662 /// features and possibly prints errors.
663 fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
664 tcx.hir().visit_item_likes_in_module(module_def_id, &mut Checker { tcx }.as_deep_visitor());
667 pub(crate) fn provide(providers: &mut Providers) {
668 *providers = Providers {
669 check_mod_unstable_api_usage,
671 lookup_stability: |tcx, id| tcx.stability().local_stability(id.expect_local()),
672 lookup_const_stability: |tcx, id| tcx.stability().local_const_stability(id.expect_local()),
673 lookup_deprecation_entry: |tcx, id| {
674 tcx.stability().local_deprecation_entry(id.expect_local())
680 struct Checker<'tcx> {
684 impl<'tcx> Visitor<'tcx> for Checker<'tcx> {
685 type NestedFilter = nested_filter::OnlyBodies;
687 /// Because stability levels are scoped lexically, we want to walk
688 /// nested items in the context of the outer item, so enable
690 fn nested_visit_map(&mut self) -> Self::Map {
694 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
696 hir::ItemKind::ExternCrate(_) => {
697 // compiler-generated `extern crate` items have a dummy span.
698 // `std` is still checked for the `restricted-std` feature.
699 if item.span.is_dummy() && item.ident.as_str() != "std" {
703 let Some(cnum) = self.tcx.extern_mod_stmt_cnum(item.def_id) else {
706 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
707 self.tcx.check_stability(def_id, Some(item.hir_id()), item.span, None);
710 // For implementations of traits, check the stability of each item
711 // individually as it's possible to have a stable trait with unstable
713 hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref t), self_ty, items, .. }) => {
714 if self.tcx.features().staged_api {
715 // If this impl block has an #[unstable] attribute, give an
716 // error if all involved types and traits are stable, because
717 // it will have no effect.
718 // See: https://github.com/rust-lang/rust/issues/55436
719 let attrs = self.tcx.hir().attrs(item.hir_id());
720 if let (Some((Stability { level: attr::Unstable { .. }, .. }, span)), _) =
721 attr::find_stability(&self.tcx.sess, attrs, item.span)
723 let mut c = CheckTraitImplStable { tcx: self.tcx, fully_stable: true };
725 c.visit_trait_ref(t);
727 self.tcx.struct_span_lint_hir(
728 INEFFECTIVE_UNSTABLE_TRAIT_IMPL,
732 .build("an `#[unstable]` annotation here has no effect")
733 .note("see issue #55436 <https://github.com/rust-lang/rust/issues/55436> for more information")
740 for impl_item_ref in items {
741 let impl_item = self.tcx.associated_item(impl_item_ref.id.def_id);
743 if let Some(def_id) = impl_item.trait_item_def_id {
744 // Pass `None` to skip deprecation warnings.
745 self.tcx.check_stability(def_id, None, impl_item_ref.span, None);
750 // There's no good place to insert stability check for non-Copy unions,
751 // so semi-randomly perform it here in stability.rs
752 hir::ItemKind::Union(..) if !self.tcx.features().untagged_unions => {
753 let ty = self.tcx.type_of(item.def_id);
754 let ty::Adt(adt_def, substs) = ty.kind() else { bug!() };
756 // Non-`Copy` fields are unstable, except for `ManuallyDrop`.
757 let param_env = self.tcx.param_env(item.def_id);
758 for field in &adt_def.non_enum_variant().fields {
759 let field_ty = field.ty(self.tcx, substs);
760 if !field_ty.ty_adt_def().map_or(false, |adt_def| adt_def.is_manually_drop())
761 && !field_ty.is_copy_modulo_regions(self.tcx.at(DUMMY_SP), param_env)
763 if field_ty.needs_drop(self.tcx, param_env) {
764 // Avoid duplicate error: This will error later anyway because fields
765 // that need drop are not allowed.
766 self.tcx.sess.delay_span_bug(
768 "union should have been rejected due to potentially dropping field",
772 &self.tcx.sess.parse_sess,
773 sym::untagged_unions,
774 self.tcx.def_span(field.did),
775 "unions with non-`Copy` fields other than `ManuallyDrop<T>` are unstable",
785 intravisit::walk_item(self, item);
788 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, id: hir::HirId) {
789 if let Some(def_id) = path.res.opt_def_id() {
790 let method_span = path.segments.last().map(|s| s.ident.span);
791 self.tcx.check_stability(def_id, Some(id), path.span, method_span)
793 intravisit::walk_path(self, path)
797 struct CheckTraitImplStable<'tcx> {
802 impl<'tcx> Visitor<'tcx> for CheckTraitImplStable<'tcx> {
803 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _id: hir::HirId) {
804 if let Some(def_id) = path.res.opt_def_id() {
805 if let Some(stab) = self.tcx.lookup_stability(def_id) {
806 self.fully_stable &= stab.level.is_stable();
809 intravisit::walk_path(self, path)
812 fn visit_trait_ref(&mut self, t: &'tcx TraitRef<'tcx>) {
813 if let Res::Def(DefKind::Trait, trait_did) = t.path.res {
814 if let Some(stab) = self.tcx.lookup_stability(trait_did) {
815 self.fully_stable &= stab.level.is_stable();
818 intravisit::walk_trait_ref(self, t)
821 fn visit_ty(&mut self, t: &'tcx Ty<'tcx>) {
822 if let TyKind::Never = t.kind {
823 self.fully_stable = false;
825 intravisit::walk_ty(self, t)
829 /// Given the list of enabled features that were not language features (i.e., that
830 /// were expected to be library features), and the list of features used from
831 /// libraries, identify activated features that don't exist and error about them.
832 pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {
834 tcx.sess.opts.debugging_opts.force_unstable_if_unmarked || tcx.features().staged_api;
836 let access_levels = &tcx.privacy_access_levels(());
837 let mut missing = MissingStabilityAnnotations { tcx, access_levels };
838 missing.check_missing_stability(CRATE_DEF_ID, tcx.hir().span(CRATE_HIR_ID));
839 tcx.hir().walk_toplevel_module(&mut missing);
840 tcx.hir().visit_all_item_likes(&mut missing.as_deep_visitor());
843 let declared_lang_features = &tcx.features().declared_lang_features;
844 let mut lang_features = FxHashSet::default();
845 for &(feature, span, since) in declared_lang_features {
846 if let Some(since) = since {
847 // Warn if the user has enabled an already-stable lang feature.
848 unnecessary_stable_feature_lint(tcx, span, feature, since);
850 if !lang_features.insert(feature) {
851 // Warn if the user enables a lang feature multiple times.
852 duplicate_feature_err(tcx.sess, span, feature);
856 let declared_lib_features = &tcx.features().declared_lib_features;
857 let mut remaining_lib_features = FxIndexMap::default();
858 for (feature, span) in declared_lib_features {
859 if !tcx.sess.opts.unstable_features.is_nightly_build() {
864 "`#![feature]` may not be used on the {} release channel",
865 env!("CFG_RELEASE_CHANNEL")
869 if remaining_lib_features.contains_key(&feature) {
870 // Warn if the user enables a lib feature multiple times.
871 duplicate_feature_err(tcx.sess, *span, *feature);
873 remaining_lib_features.insert(feature, *span);
875 // `stdbuild` has special handling for `libc`, so we need to
876 // recognise the feature when building std.
877 // Likewise, libtest is handled specially, so `test` isn't
878 // available as we'd like it to be.
879 // FIXME: only remove `libc` when `stdbuild` is active.
880 // FIXME: remove special casing for `test`.
881 remaining_lib_features.remove(&sym::libc);
882 remaining_lib_features.remove(&sym::test);
884 let check_features = |remaining_lib_features: &mut FxIndexMap<_, _>, defined_features: &[_]| {
885 for &(feature, since) in defined_features {
886 if let Some(since) = since {
887 if let Some(span) = remaining_lib_features.get(&feature) {
888 // Warn if the user has enabled an already-stable lib feature.
889 unnecessary_stable_feature_lint(tcx, *span, feature, since);
892 remaining_lib_features.remove(&feature);
893 if remaining_lib_features.is_empty() {
899 // We always collect the lib features declared in the current crate, even if there are
900 // no unknown features, because the collection also does feature attribute validation.
901 let local_defined_features = tcx.lib_features(()).to_vec();
902 if !remaining_lib_features.is_empty() {
903 check_features(&mut remaining_lib_features, &local_defined_features);
905 for &cnum in tcx.crates(()) {
906 if remaining_lib_features.is_empty() {
909 check_features(&mut remaining_lib_features, tcx.defined_lib_features(cnum));
913 for (feature, span) in remaining_lib_features {
914 struct_span_err!(tcx.sess, span, E0635, "unknown feature `{}`", feature).emit();
917 // FIXME(#44232): the `used_features` table no longer exists, so we
918 // don't lint about unused features. We should re-enable this one day!
921 fn unnecessary_stable_feature_lint(tcx: TyCtxt<'_>, span: Span, feature: Symbol, since: Symbol) {
922 tcx.struct_span_lint_hir(lint::builtin::STABLE_FEATURES, hir::CRATE_HIR_ID, span, |lint| {
924 "the feature `{}` has been stable since {} and no longer requires \
925 an attribute to enable",
932 fn duplicate_feature_err(sess: &Session, span: Span, feature: Symbol) {
933 struct_span_err!(sess, span, E0636, "the feature `{}` has already been declared", feature)
937 fn missing_const_err(session: &Session, fn_sig_span: Span, const_span: Span) {
938 const ERROR_MSG: &'static str = "attributes `#[rustc_const_unstable]` \
939 and `#[rustc_const_stable]` require \
940 the function or method to be `const`";
943 .struct_span_err(fn_sig_span, ERROR_MSG)
944 .span_help(fn_sig_span, "make the function or method const")
945 .span_label(const_span, "attribute specified here")