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_ast::Attribute;
5 use rustc_attr::{self as attr, ConstStability, Stability};
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7 use rustc_errors::struct_span_err;
9 use rustc_hir::def::{DefKind, Res};
10 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE};
11 use rustc_hir::hir_id::CRATE_HIR_ID;
12 use rustc_hir::intravisit::{self, Visitor};
13 use rustc_hir::{FieldDef, Generics, HirId, Item, TraitRef, Ty, TyKind, Variant};
14 use rustc_middle::hir::nested_filter;
15 use rustc_middle::middle::privacy::AccessLevels;
16 use rustc_middle::middle::stability::{DeprecationEntry, Index};
17 use rustc_middle::ty::{self, query::Providers, TyCtxt};
18 use rustc_session::lint;
19 use rustc_session::lint::builtin::{INEFFECTIVE_UNSTABLE_TRAIT_IMPL, USELESS_DEPRECATED};
20 use rustc_session::parse::feature_err;
21 use rustc_session::Session;
22 use rustc_span::symbol::{sym, Symbol};
23 use rustc_span::{Span, DUMMY_SP};
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> {
90 index: &'a mut Index<'tcx>,
91 parent_stab: Option<&'tcx Stability>,
92 parent_const_stab: Option<&'tcx 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
99 // stability. The stability is recorded in the index and used as the parent.
100 // If the node is a function, `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.get_attrs(def_id.to_def_id());
115 debug!("annotate(id = {:?}, attrs = {:?})", def_id, attrs);
116 let mut did_error = false;
117 if !self.tcx.features().staged_api {
118 did_error = self.forbid_staged_api_attrs(def_id, attrs, inherit_deprecation.clone());
121 let depr = if did_error { None } else { attr::find_deprecation(&self.tcx.sess, attrs) };
122 let mut is_deprecated = false;
123 if let Some((depr, span)) = &depr {
124 is_deprecated = true;
126 if kind == AnnotationKind::Prohibited || kind == AnnotationKind::DeprecationProhibited {
127 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
128 self.tcx.struct_span_lint_hir(USELESS_DEPRECATED, hir_id, *span, |lint| {
129 lint.build("this `#[deprecated]` annotation has no effect")
130 .span_suggestion_short(
132 "remove the unnecessary deprecation attribute",
134 rustc_errors::Applicability::MachineApplicable,
140 // `Deprecation` is just two pointers, no need to intern it
141 let depr_entry = DeprecationEntry::local(depr.clone(), def_id);
142 self.index.depr_map.insert(def_id, depr_entry);
143 } else if let Some(parent_depr) = self.parent_depr.clone() {
144 if inherit_deprecation.yes() {
145 is_deprecated = true;
146 info!("tagging child {:?} as deprecated from parent", def_id);
147 self.index.depr_map.insert(def_id, parent_depr);
151 if self.tcx.features().staged_api {
152 if let Some(a) = attrs.iter().find(|a| a.has_name(sym::deprecated)) {
155 .struct_span_err(a.span, "`#[deprecated]` cannot be used in staged API")
156 .span_label(a.span, "use `#[rustc_deprecated]` instead")
157 .span_label(item_sp, "")
161 self.recurse_with_stability_attrs(
162 depr.map(|(d, _)| DeprecationEntry::local(d, def_id)),
170 let (stab, const_stab) = attr::find_stability(&self.tcx.sess, attrs, item_sp);
171 let mut const_span = None;
173 let const_stab = const_stab.map(|(const_stab, const_span_node)| {
174 let const_stab = self.tcx.intern_const_stability(const_stab);
175 self.index.const_stab_map.insert(def_id, const_stab);
176 const_span = Some(const_span_node);
180 // If the current node is a function, has const stability attributes and if it doesn not have an intrinsic ABI,
181 // check if the function/method is const or the parent impl block is const
182 if let (Some(const_span), Some(fn_sig)) = (const_span, fn_sig) {
183 if fn_sig.header.abi != Abi::RustIntrinsic
184 && fn_sig.header.abi != Abi::PlatformIntrinsic
185 && !fn_sig.header.is_const()
187 if !self.in_trait_impl
188 || (self.in_trait_impl && !self.tcx.is_const_fn_raw(def_id.to_def_id()))
190 missing_const_err(&self.tcx.sess, fn_sig.span, const_span);
195 // `impl const Trait for Type` items forward their const stability to their
196 // immediate children.
197 if const_stab.is_none() {
198 debug!("annotate: const_stab not found, parent = {:?}", self.parent_const_stab);
199 if let Some(parent) = self.parent_const_stab {
200 if parent.level.is_unstable() {
201 self.index.const_stab_map.insert(def_id, parent);
206 if let Some((rustc_attr::Deprecation { is_since_rustc_version: true, .. }, span)) = &depr {
212 "rustc_deprecated attribute must be paired with \
213 either stable or unstable attribute"
219 let stab = stab.map(|(stab, span)| {
220 // Error if prohibited, or can't inherit anything from a container.
221 if kind == AnnotationKind::Prohibited
222 || (kind == AnnotationKind::Container && stab.level.is_stable() && is_deprecated)
224 self.tcx.sess.struct_span_err(span,"this stability annotation is useless")
225 .span_label(span, "useless stability annotation")
226 .span_label(item_sp, "the stability attribute annotates this item")
230 debug!("annotate: found {:?}", stab);
231 let stab = self.tcx.intern_stability(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 self.index.stab_map.insert(def_id, stab);
281 debug!("annotate: stab not found, parent = {:?}", self.parent_stab);
282 if let Some(stab) = self.parent_stab {
283 if inherit_deprecation.yes() && stab.level.is_unstable()
284 || 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<&'tcx Stability>,
303 const_stab: Option<&'tcx 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;
335 // returns true if an error occurred, used to suppress some spurious errors
336 fn forbid_staged_api_attrs(
340 inherit_deprecation: InheritDeprecation,
342 // Emit errors for non-staged-api crates.
343 let unstable_attrs = [
346 sym::rustc_deprecated,
347 sym::rustc_const_unstable,
348 sym::rustc_const_stable,
350 let mut has_error = false;
352 let name = attr.name_or_empty();
353 if unstable_attrs.contains(&name) {
358 "stability attributes may not be used outside of the standard library",
365 // Propagate unstability. This can happen even for non-staged-api crates in case
366 // -Zforce-unstable-if-unmarked is set.
367 if let Some(stab) = self.parent_stab {
368 if inherit_deprecation.yes() && stab.level.is_unstable() {
369 self.index.stab_map.insert(def_id, stab);
377 impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
378 /// Because stability levels are scoped lexically, we want to walk
379 /// nested items in the context of the outer item, so enable
381 type NestedFilter = nested_filter::All;
383 fn nested_visit_map(&mut self) -> Self::Map {
387 fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
388 let orig_in_trait_impl = self.in_trait_impl;
389 let mut kind = AnnotationKind::Required;
390 let mut const_stab_inherit = InheritConstStability::No;
391 let mut fn_sig = None;
394 // Inherent impls and foreign modules serve only as containers for other items,
395 // they don't have their own stability. They still can be annotated as unstable
396 // and propagate this unstability to children, but this annotation is completely
397 // optional. They inherit stability from their parents when unannotated.
398 hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
399 | hir::ItemKind::ForeignMod { .. } => {
400 self.in_trait_impl = false;
401 kind = AnnotationKind::Container;
403 hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => {
404 self.in_trait_impl = true;
405 kind = AnnotationKind::DeprecationProhibited;
406 const_stab_inherit = InheritConstStability::Yes;
408 hir::ItemKind::Struct(ref sd, _) => {
409 if let Some(ctor_hir_id) = sd.ctor_hir_id() {
411 self.tcx.hir().local_def_id(ctor_hir_id),
414 AnnotationKind::Required,
415 InheritDeprecation::Yes,
416 InheritConstStability::No,
417 InheritStability::Yes,
422 hir::ItemKind::Fn(ref item_fn_sig, _, _) => {
423 fn_sig = Some(item_fn_sig);
433 InheritDeprecation::Yes,
435 InheritStability::No,
436 |v| intravisit::walk_item(v, i),
438 self.in_trait_impl = orig_in_trait_impl;
441 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
442 let fn_sig = match ti.kind {
443 hir::TraitItemKind::Fn(ref fn_sig, _) => Some(fn_sig),
451 AnnotationKind::Required,
452 InheritDeprecation::Yes,
453 InheritConstStability::No,
454 InheritStability::No,
456 intravisit::walk_trait_item(v, ti);
461 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
463 if self.in_trait_impl { AnnotationKind::Prohibited } else { AnnotationKind::Required };
465 let fn_sig = match ii.kind {
466 hir::ImplItemKind::Fn(ref fn_sig, _) => Some(fn_sig),
475 InheritDeprecation::Yes,
476 InheritConstStability::No,
477 InheritStability::No,
479 intravisit::walk_impl_item(v, ii);
484 fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) {
486 self.tcx.hir().local_def_id(var.id),
489 AnnotationKind::Required,
490 InheritDeprecation::Yes,
491 InheritConstStability::No,
492 InheritStability::Yes,
494 if let Some(ctor_hir_id) = var.data.ctor_hir_id() {
496 v.tcx.hir().local_def_id(ctor_hir_id),
499 AnnotationKind::Required,
500 InheritDeprecation::Yes,
501 InheritConstStability::No,
502 InheritStability::No,
507 intravisit::walk_variant(v, var, g, item_id)
512 fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
514 self.tcx.hir().local_def_id(s.hir_id),
517 AnnotationKind::Required,
518 InheritDeprecation::Yes,
519 InheritConstStability::No,
520 InheritStability::Yes,
522 intravisit::walk_field_def(v, s);
527 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
532 AnnotationKind::Required,
533 InheritDeprecation::Yes,
534 InheritConstStability::No,
535 InheritStability::No,
537 intravisit::walk_foreign_item(v, i);
542 fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
543 let kind = match &p.kind {
544 // Allow stability attributes on default generic arguments.
545 hir::GenericParamKind::Type { default: Some(_), .. }
546 | hir::GenericParamKind::Const { default: Some(_), .. } => AnnotationKind::Container,
547 _ => AnnotationKind::Prohibited,
551 self.tcx.hir().local_def_id(p.hir_id),
555 InheritDeprecation::No,
556 InheritConstStability::No,
557 InheritStability::No,
559 intravisit::walk_generic_param(v, p);
565 struct MissingStabilityAnnotations<'tcx> {
567 access_levels: &'tcx AccessLevels,
570 impl<'tcx> MissingStabilityAnnotations<'tcx> {
571 fn check_missing_stability(&self, def_id: LocalDefId, span: Span) {
572 let stab = self.tcx.stability().local_stability(def_id);
573 if !self.tcx.sess.opts.test && stab.is_none() && self.access_levels.is_reachable(def_id) {
574 let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
575 self.tcx.sess.span_err(span, &format!("{} has missing stability attribute", descr));
579 fn check_missing_const_stability(&self, def_id: LocalDefId, span: Span) {
580 if !self.tcx.features().staged_api {
584 let is_const = self.tcx.is_const_fn(def_id.to_def_id());
587 .lookup_stability(def_id)
588 .map_or(false, |stability| stability.level.is_stable());
589 let missing_const_stability_attribute = self.tcx.lookup_const_stability(def_id).is_none();
590 let is_reachable = self.access_levels.is_reachable(def_id);
592 if is_const && is_stable && missing_const_stability_attribute && is_reachable {
593 let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
594 self.tcx.sess.span_err(span, &format!("{descr} has missing const stability attribute"));
599 impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> {
600 type NestedFilter = nested_filter::OnlyBodies;
602 fn nested_visit_map(&mut self) -> Self::Map {
606 fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
607 // Inherent impls and foreign modules serve only as containers for other items,
608 // they don't have their own stability. They still can be annotated as unstable
609 // and propagate this unstability to children, but this annotation is completely
610 // optional. They inherit stability from their parents when unannotated.
613 hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
614 | hir::ItemKind::ForeignMod { .. }
616 self.check_missing_stability(i.def_id, i.span);
619 // Ensure stable `const fn` have a const stability attribute.
620 self.check_missing_const_stability(i.def_id, i.span);
622 intravisit::walk_item(self, i)
625 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
626 self.check_missing_stability(ti.def_id, ti.span);
627 intravisit::walk_trait_item(self, ti);
630 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
631 let impl_def_id = self.tcx.hir().get_parent_item(ii.hir_id());
632 if self.tcx.impl_trait_ref(impl_def_id).is_none() {
633 self.check_missing_stability(ii.def_id, ii.span);
634 self.check_missing_const_stability(ii.def_id, ii.span);
636 intravisit::walk_impl_item(self, ii);
639 fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) {
640 self.check_missing_stability(self.tcx.hir().local_def_id(var.id), var.span);
641 intravisit::walk_variant(self, var, g, item_id);
644 fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
645 self.check_missing_stability(self.tcx.hir().local_def_id(s.hir_id), s.span);
646 intravisit::walk_field_def(self, s);
649 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
650 self.check_missing_stability(i.def_id, i.span);
651 intravisit::walk_foreign_item(self, i);
653 // Note that we don't need to `check_missing_stability` for default generic parameters,
654 // as we assume that any default generic parameters without attributes are automatically
655 // stable (assuming they have not inherited instability from their parent).
658 fn stability_index<'tcx>(tcx: TyCtxt<'tcx>, (): ()) -> Index<'tcx> {
660 tcx.sess.opts.debugging_opts.force_unstable_if_unmarked || tcx.features().staged_api;
661 let mut staged_api = FxHashMap::default();
662 staged_api.insert(LOCAL_CRATE, is_staged_api);
663 let mut index = Index {
665 stab_map: Default::default(),
666 const_stab_map: Default::default(),
667 depr_map: Default::default(),
668 active_features: Default::default(),
671 let active_lib_features = &tcx.features().declared_lib_features;
672 let active_lang_features = &tcx.features().declared_lang_features;
674 // Put the active features into a map for quick lookup.
675 index.active_features = active_lib_features
678 .chain(active_lang_features.iter().map(|&(s, ..)| s))
682 let mut annotator = Annotator {
686 parent_const_stab: None,
688 in_trait_impl: false,
691 // If the `-Z force-unstable-if-unmarked` flag is passed then we provide
692 // a parent stability annotation which indicates that this is private
693 // with the `rustc_private` feature. This is intended for use when
694 // compiling `librustc_*` crates themselves so we can leverage crates.io
695 // while maintaining the invariant that all sysroot crates are unstable
696 // by default and are unable to be used.
697 if tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
698 let reason = "this crate is being loaded from the sysroot, an \
699 unstable location; did you mean to load this crate \
700 from crates.io via `Cargo.toml` instead?";
701 let stability = tcx.intern_stability(Stability {
702 level: attr::StabilityLevel::Unstable {
703 reason: Some(Symbol::intern(reason)),
704 issue: NonZeroU32::new(27812),
707 feature: sym::rustc_private,
709 annotator.parent_stab = Some(stability);
714 tcx.hir().span(CRATE_HIR_ID),
716 AnnotationKind::Required,
717 InheritDeprecation::Yes,
718 InheritConstStability::No,
719 InheritStability::No,
720 |v| tcx.hir().walk_toplevel_module(v),
726 /// Cross-references the feature names of unstable APIs with enabled
727 /// features and possibly prints errors.
728 fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
729 tcx.hir().visit_item_likes_in_module(module_def_id, &mut Checker { tcx }.as_deep_visitor());
732 pub(crate) fn provide(providers: &mut Providers) {
733 *providers = Providers { check_mod_unstable_api_usage, stability_index, ..*providers };
736 struct Checker<'tcx> {
740 impl<'tcx> Visitor<'tcx> for Checker<'tcx> {
741 type NestedFilter = nested_filter::OnlyBodies;
743 /// Because stability levels are scoped lexically, we want to walk
744 /// nested items in the context of the outer item, so enable
746 fn nested_visit_map(&mut self) -> Self::Map {
750 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
752 hir::ItemKind::ExternCrate(_) => {
753 // compiler-generated `extern crate` items have a dummy span.
754 // `std` is still checked for the `restricted-std` feature.
755 if item.span.is_dummy() && item.ident.as_str() != "std" {
759 let cnum = match self.tcx.extern_mod_stmt_cnum(item.def_id) {
763 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
764 self.tcx.check_stability(def_id, Some(item.hir_id()), item.span, None);
767 // For implementations of traits, check the stability of each item
768 // individually as it's possible to have a stable trait with unstable
770 hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref t), self_ty, items, .. }) => {
771 if self.tcx.features().staged_api {
772 // If this impl block has an #[unstable] attribute, give an
773 // error if all involved types and traits are stable, because
774 // it will have no effect.
775 // See: https://github.com/rust-lang/rust/issues/55436
776 let attrs = self.tcx.hir().attrs(item.hir_id());
777 if let (Some((Stability { level: attr::Unstable { .. }, .. }, span)), _) =
778 attr::find_stability(&self.tcx.sess, attrs, item.span)
780 let mut c = CheckTraitImplStable { tcx: self.tcx, fully_stable: true };
782 c.visit_trait_ref(t);
784 self.tcx.struct_span_lint_hir(
785 INEFFECTIVE_UNSTABLE_TRAIT_IMPL,
789 .build("an `#[unstable]` annotation here has no effect")
790 .note("see issue #55436 <https://github.com/rust-lang/rust/issues/55436> for more information")
797 for impl_item_ref in items {
798 let impl_item = self.tcx.associated_item(impl_item_ref.id.def_id);
800 if let Some(def_id) = impl_item.trait_item_def_id {
801 // Pass `None` to skip deprecation warnings.
802 self.tcx.check_stability(def_id, None, impl_item_ref.span, None);
807 // There's no good place to insert stability check for non-Copy unions,
808 // so semi-randomly perform it here in stability.rs
809 hir::ItemKind::Union(..) if !self.tcx.features().untagged_unions => {
810 let ty = self.tcx.type_of(item.def_id);
811 let (adt_def, substs) = match ty.kind() {
812 ty::Adt(adt_def, substs) => (adt_def, substs),
816 // Non-`Copy` fields are unstable, except for `ManuallyDrop`.
817 let param_env = self.tcx.param_env(item.def_id);
818 for field in &adt_def.non_enum_variant().fields {
819 let field_ty = field.ty(self.tcx, substs);
820 if !field_ty.ty_adt_def().map_or(false, |adt_def| adt_def.is_manually_drop())
821 && !field_ty.is_copy_modulo_regions(self.tcx.at(DUMMY_SP), param_env)
823 if field_ty.needs_drop(self.tcx, param_env) {
824 // Avoid duplicate error: This will error later anyway because fields
825 // that need drop are not allowed.
826 self.tcx.sess.delay_span_bug(
828 "union should have been rejected due to potentially dropping field",
832 &self.tcx.sess.parse_sess,
833 sym::untagged_unions,
834 self.tcx.def_span(field.did),
835 "unions with non-`Copy` fields other than `ManuallyDrop<T>` are unstable",
845 intravisit::walk_item(self, item);
848 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, id: hir::HirId) {
849 if let Some(def_id) = path.res.opt_def_id() {
850 let method_span = path.segments.last().map(|s| s.ident.span);
851 self.tcx.check_stability(def_id, Some(id), path.span, method_span)
853 intravisit::walk_path(self, path)
857 struct CheckTraitImplStable<'tcx> {
862 impl<'tcx> Visitor<'tcx> for CheckTraitImplStable<'tcx> {
863 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _id: hir::HirId) {
864 if let Some(def_id) = path.res.opt_def_id() {
865 if let Some(stab) = self.tcx.lookup_stability(def_id) {
866 self.fully_stable &= stab.level.is_stable();
869 intravisit::walk_path(self, path)
872 fn visit_trait_ref(&mut self, t: &'tcx TraitRef<'tcx>) {
873 if let Res::Def(DefKind::Trait, trait_did) = t.path.res {
874 if let Some(stab) = self.tcx.lookup_stability(trait_did) {
875 self.fully_stable &= stab.level.is_stable();
878 intravisit::walk_trait_ref(self, t)
881 fn visit_ty(&mut self, t: &'tcx Ty<'tcx>) {
882 if let TyKind::Never = t.kind {
883 self.fully_stable = false;
885 intravisit::walk_ty(self, t)
889 /// Given the list of enabled features that were not language features (i.e., that
890 /// were expected to be library features), and the list of features used from
891 /// libraries, identify activated features that don't exist and error about them.
892 pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {
893 let access_levels = &tcx.privacy_access_levels(());
895 if tcx.stability().staged_api[&LOCAL_CRATE] {
896 let mut missing = MissingStabilityAnnotations { tcx, access_levels };
897 missing.check_missing_stability(CRATE_DEF_ID, tcx.hir().span(CRATE_HIR_ID));
898 tcx.hir().walk_toplevel_module(&mut missing);
899 tcx.hir().visit_all_item_likes(&mut missing.as_deep_visitor());
902 let declared_lang_features = &tcx.features().declared_lang_features;
903 let mut lang_features = FxHashSet::default();
904 for &(feature, span, since) in declared_lang_features {
905 if let Some(since) = since {
906 // Warn if the user has enabled an already-stable lang feature.
907 unnecessary_stable_feature_lint(tcx, span, feature, since);
909 if !lang_features.insert(feature) {
910 // Warn if the user enables a lang feature multiple times.
911 duplicate_feature_err(tcx.sess, span, feature);
915 let declared_lib_features = &tcx.features().declared_lib_features;
916 let mut remaining_lib_features = FxHashMap::default();
917 for (feature, span) in declared_lib_features {
918 if !tcx.sess.opts.unstable_features.is_nightly_build() {
923 "`#![feature]` may not be used on the {} release channel",
924 env!("CFG_RELEASE_CHANNEL")
928 if remaining_lib_features.contains_key(&feature) {
929 // Warn if the user enables a lib feature multiple times.
930 duplicate_feature_err(tcx.sess, *span, *feature);
932 remaining_lib_features.insert(feature, *span);
934 // `stdbuild` has special handling for `libc`, so we need to
935 // recognise the feature when building std.
936 // Likewise, libtest is handled specially, so `test` isn't
937 // available as we'd like it to be.
938 // FIXME: only remove `libc` when `stdbuild` is active.
939 // FIXME: remove special casing for `test`.
940 remaining_lib_features.remove(&sym::libc);
941 remaining_lib_features.remove(&sym::test);
943 let check_features = |remaining_lib_features: &mut FxHashMap<_, _>, defined_features: &[_]| {
944 for &(feature, since) in defined_features {
945 if let Some(since) = since {
946 if let Some(span) = remaining_lib_features.get(&feature) {
947 // Warn if the user has enabled an already-stable lib feature.
948 unnecessary_stable_feature_lint(tcx, *span, feature, since);
951 remaining_lib_features.remove(&feature);
952 if remaining_lib_features.is_empty() {
958 // We always collect the lib features declared in the current crate, even if there are
959 // no unknown features, because the collection also does feature attribute validation.
960 let local_defined_features = tcx.lib_features(()).to_vec();
961 if !remaining_lib_features.is_empty() {
962 check_features(&mut remaining_lib_features, &local_defined_features);
964 for &cnum in tcx.crates(()) {
965 if remaining_lib_features.is_empty() {
968 check_features(&mut remaining_lib_features, tcx.defined_lib_features(cnum));
972 for (feature, span) in remaining_lib_features {
973 struct_span_err!(tcx.sess, span, E0635, "unknown feature `{}`", feature).emit();
976 // FIXME(#44232): the `used_features` table no longer exists, so we
977 // don't lint about unused features. We should re-enable this one day!
980 fn unnecessary_stable_feature_lint(tcx: TyCtxt<'_>, span: Span, feature: Symbol, since: Symbol) {
981 tcx.struct_span_lint_hir(lint::builtin::STABLE_FEATURES, hir::CRATE_HIR_ID, span, |lint| {
983 "the feature `{}` has been stable since {} and no longer requires \
984 an attribute to enable",
991 fn duplicate_feature_err(sess: &Session, span: Span, feature: Symbol) {
992 struct_span_err!(sess, span, E0636, "the feature `{}` has already been declared", feature)
996 fn missing_const_err(session: &Session, fn_sig_span: Span, const_span: Span) {
997 const ERROR_MSG: &'static str = "attributes `#[rustc_const_unstable]` \
998 and `#[rustc_const_stable]` require \
999 the function or method to be `const`";
1002 .struct_span_err(fn_sig_span, ERROR_MSG)
1003 .span_help(fn_sig_span, "make the function or method const")
1004 .span_label(const_span, "attribute specified here")