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> {
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
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 self.index.const_stab_map.insert(def_id, const_stab);
175 const_span = Some(const_span_node);
179 // If the current node is a function, has const stability attributes and if it doesn not have an intrinsic ABI,
180 // check if the function/method is const or the parent impl block is const
181 if let (Some(const_span), Some(fn_sig)) = (const_span, fn_sig) {
182 if fn_sig.header.abi != Abi::RustIntrinsic
183 && fn_sig.header.abi != Abi::PlatformIntrinsic
184 && !fn_sig.header.is_const()
186 if !self.in_trait_impl
187 || (self.in_trait_impl && !self.tcx.is_const_fn_raw(def_id.to_def_id()))
189 missing_const_err(&self.tcx.sess, fn_sig.span, const_span);
194 // `impl const Trait for Type` items forward their const stability to their
195 // immediate children.
196 if const_stab.is_none() {
197 debug!("annotate: const_stab not found, parent = {:?}", self.parent_const_stab);
198 if let Some(parent) = self.parent_const_stab {
199 if parent.level.is_unstable() {
200 self.index.const_stab_map.insert(def_id, parent);
205 if let Some((rustc_attr::Deprecation { is_since_rustc_version: true, .. }, span)) = &depr {
211 "rustc_deprecated attribute must be paired with \
212 either stable or unstable attribute"
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 self.index.stab_map.insert(def_id, stab);
279 debug!("annotate: stab not found, parent = {:?}", self.parent_stab);
280 if let Some(stab) = self.parent_stab {
281 if inherit_deprecation.yes() && stab.level.is_unstable()
282 || inherit_from_parent.yes()
284 self.index.stab_map.insert(def_id, stab);
289 self.recurse_with_stability_attrs(
290 depr.map(|(d, _)| DeprecationEntry::local(d, def_id)),
292 if inherit_const_stability.yes() { const_stab } else { None },
297 fn recurse_with_stability_attrs(
299 depr: Option<DeprecationEntry>,
300 stab: Option<Stability>,
301 const_stab: Option<ConstStability>,
302 f: impl FnOnce(&mut Self),
304 // These will be `Some` if this item changes the corresponding stability attribute.
305 let mut replaced_parent_depr = None;
306 let mut replaced_parent_stab = None;
307 let mut replaced_parent_const_stab = None;
309 if let Some(depr) = depr {
310 replaced_parent_depr = Some(replace(&mut self.parent_depr, Some(depr)));
312 if let Some(stab) = stab {
313 replaced_parent_stab = Some(replace(&mut self.parent_stab, Some(stab)));
315 if let Some(const_stab) = const_stab {
316 replaced_parent_const_stab =
317 Some(replace(&mut self.parent_const_stab, Some(const_stab)));
322 if let Some(orig_parent_depr) = replaced_parent_depr {
323 self.parent_depr = orig_parent_depr;
325 if let Some(orig_parent_stab) = replaced_parent_stab {
326 self.parent_stab = orig_parent_stab;
328 if let Some(orig_parent_const_stab) = replaced_parent_const_stab {
329 self.parent_const_stab = orig_parent_const_stab;
333 // returns true if an error occurred, used to suppress some spurious errors
334 fn forbid_staged_api_attrs(
338 inherit_deprecation: InheritDeprecation,
340 // Emit errors for non-staged-api crates.
341 let unstable_attrs = [
344 sym::rustc_deprecated,
345 sym::rustc_const_unstable,
346 sym::rustc_const_stable,
348 let mut has_error = false;
350 let name = attr.name_or_empty();
351 if unstable_attrs.contains(&name) {
356 "stability attributes may not be used outside of the standard library",
363 // Propagate unstability. This can happen even for non-staged-api crates in case
364 // -Zforce-unstable-if-unmarked is set.
365 if let Some(stab) = self.parent_stab {
366 if inherit_deprecation.yes() && stab.level.is_unstable() {
367 self.index.stab_map.insert(def_id, stab);
375 impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
376 /// Because stability levels are scoped lexically, we want to walk
377 /// nested items in the context of the outer item, so enable
379 type NestedFilter = nested_filter::All;
381 fn nested_visit_map(&mut self) -> Self::Map {
385 fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
386 let orig_in_trait_impl = self.in_trait_impl;
387 let mut kind = AnnotationKind::Required;
388 let mut const_stab_inherit = InheritConstStability::No;
389 let mut fn_sig = None;
392 // Inherent impls and foreign modules serve only as containers for other items,
393 // they don't have their own stability. They still can be annotated as unstable
394 // and propagate this unstability to children, but this annotation is completely
395 // optional. They inherit stability from their parents when unannotated.
396 hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
397 | hir::ItemKind::ForeignMod { .. } => {
398 self.in_trait_impl = false;
399 kind = AnnotationKind::Container;
401 hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => {
402 self.in_trait_impl = true;
403 kind = AnnotationKind::DeprecationProhibited;
404 const_stab_inherit = InheritConstStability::Yes;
406 hir::ItemKind::Struct(ref sd, _) => {
407 if let Some(ctor_hir_id) = sd.ctor_hir_id() {
409 self.tcx.hir().local_def_id(ctor_hir_id),
412 AnnotationKind::Required,
413 InheritDeprecation::Yes,
414 InheritConstStability::No,
415 InheritStability::Yes,
420 hir::ItemKind::Fn(ref item_fn_sig, _, _) => {
421 fn_sig = Some(item_fn_sig);
431 InheritDeprecation::Yes,
433 InheritStability::No,
434 |v| intravisit::walk_item(v, i),
436 self.in_trait_impl = orig_in_trait_impl;
439 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
440 let fn_sig = match ti.kind {
441 hir::TraitItemKind::Fn(ref fn_sig, _) => Some(fn_sig),
449 AnnotationKind::Required,
450 InheritDeprecation::Yes,
451 InheritConstStability::No,
452 InheritStability::No,
454 intravisit::walk_trait_item(v, ti);
459 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
461 if self.in_trait_impl { AnnotationKind::Prohibited } else { AnnotationKind::Required };
463 let fn_sig = match ii.kind {
464 hir::ImplItemKind::Fn(ref fn_sig, _) => Some(fn_sig),
473 InheritDeprecation::Yes,
474 InheritConstStability::No,
475 InheritStability::No,
477 intravisit::walk_impl_item(v, ii);
482 fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) {
484 self.tcx.hir().local_def_id(var.id),
487 AnnotationKind::Required,
488 InheritDeprecation::Yes,
489 InheritConstStability::No,
490 InheritStability::Yes,
492 if let Some(ctor_hir_id) = var.data.ctor_hir_id() {
494 v.tcx.hir().local_def_id(ctor_hir_id),
497 AnnotationKind::Required,
498 InheritDeprecation::Yes,
499 InheritConstStability::No,
500 InheritStability::No,
505 intravisit::walk_variant(v, var, g, item_id)
510 fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
512 self.tcx.hir().local_def_id(s.hir_id),
515 AnnotationKind::Required,
516 InheritDeprecation::Yes,
517 InheritConstStability::No,
518 InheritStability::Yes,
520 intravisit::walk_field_def(v, s);
525 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
530 AnnotationKind::Required,
531 InheritDeprecation::Yes,
532 InheritConstStability::No,
533 InheritStability::No,
535 intravisit::walk_foreign_item(v, i);
540 fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
541 let kind = match &p.kind {
542 // Allow stability attributes on default generic arguments.
543 hir::GenericParamKind::Type { default: Some(_), .. }
544 | hir::GenericParamKind::Const { default: Some(_), .. } => AnnotationKind::Container,
545 _ => AnnotationKind::Prohibited,
549 self.tcx.hir().local_def_id(p.hir_id),
553 InheritDeprecation::No,
554 InheritConstStability::No,
555 InheritStability::No,
557 intravisit::walk_generic_param(v, p);
563 struct MissingStabilityAnnotations<'tcx> {
565 access_levels: &'tcx AccessLevels,
568 impl<'tcx> MissingStabilityAnnotations<'tcx> {
569 fn check_missing_stability(&self, def_id: LocalDefId, span: Span) {
570 let stab = self.tcx.stability().local_stability(def_id);
571 if !self.tcx.sess.opts.test && stab.is_none() && self.access_levels.is_reachable(def_id) {
572 let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
573 self.tcx.sess.span_err(span, &format!("{} has missing stability attribute", descr));
577 fn check_missing_const_stability(&self, def_id: LocalDefId, span: Span) {
578 if !self.tcx.features().staged_api {
582 let is_const = self.tcx.is_const_fn(def_id.to_def_id());
585 .lookup_stability(def_id)
586 .map_or(false, |stability| stability.level.is_stable());
587 let missing_const_stability_attribute = self.tcx.lookup_const_stability(def_id).is_none();
588 let is_reachable = self.access_levels.is_reachable(def_id);
590 if is_const && is_stable && missing_const_stability_attribute && is_reachable {
591 let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
592 self.tcx.sess.span_err(span, &format!("{descr} has missing const stability attribute"));
597 impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> {
598 type NestedFilter = nested_filter::OnlyBodies;
600 fn nested_visit_map(&mut self) -> Self::Map {
604 fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
605 // Inherent impls and foreign modules serve only as containers for other items,
606 // they don't have their own stability. They still can be annotated as unstable
607 // and propagate this unstability to children, but this annotation is completely
608 // optional. They inherit stability from their parents when unannotated.
611 hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
612 | hir::ItemKind::ForeignMod { .. }
614 self.check_missing_stability(i.def_id, i.span);
617 // Ensure stable `const fn` have a const stability attribute.
618 self.check_missing_const_stability(i.def_id, i.span);
620 intravisit::walk_item(self, i)
623 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
624 self.check_missing_stability(ti.def_id, ti.span);
625 intravisit::walk_trait_item(self, ti);
628 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
629 let impl_def_id = self.tcx.hir().get_parent_item(ii.hir_id());
630 if self.tcx.impl_trait_ref(impl_def_id).is_none() {
631 self.check_missing_stability(ii.def_id, ii.span);
632 self.check_missing_const_stability(ii.def_id, ii.span);
634 intravisit::walk_impl_item(self, ii);
637 fn visit_variant(&mut self, var: &'tcx Variant<'tcx>, g: &'tcx Generics<'tcx>, item_id: HirId) {
638 self.check_missing_stability(self.tcx.hir().local_def_id(var.id), var.span);
639 intravisit::walk_variant(self, var, g, item_id);
642 fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
643 self.check_missing_stability(self.tcx.hir().local_def_id(s.hir_id), s.span);
644 intravisit::walk_field_def(self, s);
647 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
648 self.check_missing_stability(i.def_id, i.span);
649 intravisit::walk_foreign_item(self, i);
651 // Note that we don't need to `check_missing_stability` for default generic parameters,
652 // as we assume that any default generic parameters without attributes are automatically
653 // stable (assuming they have not inherited instability from their parent).
656 fn stability_index(tcx: TyCtxt<'_>, (): ()) -> Index {
658 tcx.sess.opts.debugging_opts.force_unstable_if_unmarked || tcx.features().staged_api;
659 let mut staged_api = FxHashMap::default();
660 staged_api.insert(LOCAL_CRATE, is_staged_api);
661 let mut index = Index {
663 stab_map: Default::default(),
664 const_stab_map: Default::default(),
665 depr_map: Default::default(),
666 active_features: Default::default(),
669 let active_lib_features = &tcx.features().declared_lib_features;
670 let active_lang_features = &tcx.features().declared_lang_features;
672 // Put the active features into a map for quick lookup.
673 index.active_features = active_lib_features
676 .chain(active_lang_features.iter().map(|&(s, ..)| s))
680 let mut annotator = Annotator {
684 parent_const_stab: None,
686 in_trait_impl: false,
689 // If the `-Z force-unstable-if-unmarked` flag is passed then we provide
690 // a parent stability annotation which indicates that this is private
691 // with the `rustc_private` feature. This is intended for use when
692 // compiling `librustc_*` crates themselves so we can leverage crates.io
693 // while maintaining the invariant that all sysroot crates are unstable
694 // by default and are unable to be used.
695 if tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
696 let reason = "this crate is being loaded from the sysroot, an \
697 unstable location; did you mean to load this crate \
698 from crates.io via `Cargo.toml` instead?";
699 let stability = Stability {
700 level: attr::StabilityLevel::Unstable {
701 reason: Some(Symbol::intern(reason)),
702 issue: NonZeroU32::new(27812),
705 feature: sym::rustc_private,
707 annotator.parent_stab = Some(stability);
712 tcx.hir().span(CRATE_HIR_ID),
714 AnnotationKind::Required,
715 InheritDeprecation::Yes,
716 InheritConstStability::No,
717 InheritStability::No,
718 |v| tcx.hir().walk_toplevel_module(v),
724 /// Cross-references the feature names of unstable APIs with enabled
725 /// features and possibly prints errors.
726 fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
727 tcx.hir().visit_item_likes_in_module(module_def_id, &mut Checker { tcx }.as_deep_visitor());
730 pub(crate) fn provide(providers: &mut Providers) {
731 *providers = Providers { check_mod_unstable_api_usage, stability_index, ..*providers };
734 struct Checker<'tcx> {
738 impl<'tcx> Visitor<'tcx> for Checker<'tcx> {
739 type NestedFilter = nested_filter::OnlyBodies;
741 /// Because stability levels are scoped lexically, we want to walk
742 /// nested items in the context of the outer item, so enable
744 fn nested_visit_map(&mut self) -> Self::Map {
748 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
750 hir::ItemKind::ExternCrate(_) => {
751 // compiler-generated `extern crate` items have a dummy span.
752 // `std` is still checked for the `restricted-std` feature.
753 if item.span.is_dummy() && item.ident.as_str() != "std" {
757 let Some(cnum) = self.tcx.extern_mod_stmt_cnum(item.def_id) else {
760 let def_id = DefId { krate: cnum, index: CRATE_DEF_INDEX };
761 self.tcx.check_stability(def_id, Some(item.hir_id()), item.span, None);
764 // For implementations of traits, check the stability of each item
765 // individually as it's possible to have a stable trait with unstable
767 hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref t), self_ty, items, .. }) => {
768 if self.tcx.features().staged_api {
769 // If this impl block has an #[unstable] attribute, give an
770 // error if all involved types and traits are stable, because
771 // it will have no effect.
772 // See: https://github.com/rust-lang/rust/issues/55436
773 let attrs = self.tcx.hir().attrs(item.hir_id());
774 if let (Some((Stability { level: attr::Unstable { .. }, .. }, span)), _) =
775 attr::find_stability(&self.tcx.sess, attrs, item.span)
777 let mut c = CheckTraitImplStable { tcx: self.tcx, fully_stable: true };
779 c.visit_trait_ref(t);
781 self.tcx.struct_span_lint_hir(
782 INEFFECTIVE_UNSTABLE_TRAIT_IMPL,
786 .build("an `#[unstable]` annotation here has no effect")
787 .note("see issue #55436 <https://github.com/rust-lang/rust/issues/55436> for more information")
794 for impl_item_ref in items {
795 let impl_item = self.tcx.associated_item(impl_item_ref.id.def_id);
797 if let Some(def_id) = impl_item.trait_item_def_id {
798 // Pass `None` to skip deprecation warnings.
799 self.tcx.check_stability(def_id, None, impl_item_ref.span, None);
804 // There's no good place to insert stability check for non-Copy unions,
805 // so semi-randomly perform it here in stability.rs
806 hir::ItemKind::Union(..) if !self.tcx.features().untagged_unions => {
807 let ty = self.tcx.type_of(item.def_id);
808 let ty::Adt(adt_def, substs) = ty.kind() else { bug!() };
810 // Non-`Copy` fields are unstable, except for `ManuallyDrop`.
811 let param_env = self.tcx.param_env(item.def_id);
812 for field in &adt_def.non_enum_variant().fields {
813 let field_ty = field.ty(self.tcx, substs);
814 if !field_ty.ty_adt_def().map_or(false, |adt_def| adt_def.is_manually_drop())
815 && !field_ty.is_copy_modulo_regions(self.tcx.at(DUMMY_SP), param_env)
817 if field_ty.needs_drop(self.tcx, param_env) {
818 // Avoid duplicate error: This will error later anyway because fields
819 // that need drop are not allowed.
820 self.tcx.sess.delay_span_bug(
822 "union should have been rejected due to potentially dropping field",
826 &self.tcx.sess.parse_sess,
827 sym::untagged_unions,
828 self.tcx.def_span(field.did),
829 "unions with non-`Copy` fields other than `ManuallyDrop<T>` are unstable",
839 intravisit::walk_item(self, item);
842 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, id: hir::HirId) {
843 if let Some(def_id) = path.res.opt_def_id() {
844 let method_span = path.segments.last().map(|s| s.ident.span);
845 self.tcx.check_stability(def_id, Some(id), path.span, method_span)
847 intravisit::walk_path(self, path)
851 struct CheckTraitImplStable<'tcx> {
856 impl<'tcx> Visitor<'tcx> for CheckTraitImplStable<'tcx> {
857 fn visit_path(&mut self, path: &'tcx hir::Path<'tcx>, _id: hir::HirId) {
858 if let Some(def_id) = path.res.opt_def_id() {
859 if let Some(stab) = self.tcx.lookup_stability(def_id) {
860 self.fully_stable &= stab.level.is_stable();
863 intravisit::walk_path(self, path)
866 fn visit_trait_ref(&mut self, t: &'tcx TraitRef<'tcx>) {
867 if let Res::Def(DefKind::Trait, trait_did) = t.path.res {
868 if let Some(stab) = self.tcx.lookup_stability(trait_did) {
869 self.fully_stable &= stab.level.is_stable();
872 intravisit::walk_trait_ref(self, t)
875 fn visit_ty(&mut self, t: &'tcx Ty<'tcx>) {
876 if let TyKind::Never = t.kind {
877 self.fully_stable = false;
879 intravisit::walk_ty(self, t)
883 /// Given the list of enabled features that were not language features (i.e., that
884 /// were expected to be library features), and the list of features used from
885 /// libraries, identify activated features that don't exist and error about them.
886 pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {
887 let access_levels = &tcx.privacy_access_levels(());
889 if tcx.stability().staged_api[&LOCAL_CRATE] {
890 let mut missing = MissingStabilityAnnotations { tcx, access_levels };
891 missing.check_missing_stability(CRATE_DEF_ID, tcx.hir().span(CRATE_HIR_ID));
892 tcx.hir().walk_toplevel_module(&mut missing);
893 tcx.hir().visit_all_item_likes(&mut missing.as_deep_visitor());
896 let declared_lang_features = &tcx.features().declared_lang_features;
897 let mut lang_features = FxHashSet::default();
898 for &(feature, span, since) in declared_lang_features {
899 if let Some(since) = since {
900 // Warn if the user has enabled an already-stable lang feature.
901 unnecessary_stable_feature_lint(tcx, span, feature, since);
903 if !lang_features.insert(feature) {
904 // Warn if the user enables a lang feature multiple times.
905 duplicate_feature_err(tcx.sess, span, feature);
909 let declared_lib_features = &tcx.features().declared_lib_features;
910 let mut remaining_lib_features = FxHashMap::default();
911 for (feature, span) in declared_lib_features {
912 if !tcx.sess.opts.unstable_features.is_nightly_build() {
917 "`#![feature]` may not be used on the {} release channel",
918 env!("CFG_RELEASE_CHANNEL")
922 if remaining_lib_features.contains_key(&feature) {
923 // Warn if the user enables a lib feature multiple times.
924 duplicate_feature_err(tcx.sess, *span, *feature);
926 remaining_lib_features.insert(feature, *span);
928 // `stdbuild` has special handling for `libc`, so we need to
929 // recognise the feature when building std.
930 // Likewise, libtest is handled specially, so `test` isn't
931 // available as we'd like it to be.
932 // FIXME: only remove `libc` when `stdbuild` is active.
933 // FIXME: remove special casing for `test`.
934 remaining_lib_features.remove(&sym::libc);
935 remaining_lib_features.remove(&sym::test);
937 let check_features = |remaining_lib_features: &mut FxHashMap<_, _>, defined_features: &[_]| {
938 for &(feature, since) in defined_features {
939 if let Some(since) = since {
940 if let Some(span) = remaining_lib_features.get(&feature) {
941 // Warn if the user has enabled an already-stable lib feature.
942 unnecessary_stable_feature_lint(tcx, *span, feature, since);
945 remaining_lib_features.remove(&feature);
946 if remaining_lib_features.is_empty() {
952 // We always collect the lib features declared in the current crate, even if there are
953 // no unknown features, because the collection also does feature attribute validation.
954 let local_defined_features = tcx.lib_features(()).to_vec();
955 if !remaining_lib_features.is_empty() {
956 check_features(&mut remaining_lib_features, &local_defined_features);
958 for &cnum in tcx.crates(()) {
959 if remaining_lib_features.is_empty() {
962 check_features(&mut remaining_lib_features, tcx.defined_lib_features(cnum));
966 for (feature, span) in remaining_lib_features {
967 struct_span_err!(tcx.sess, span, E0635, "unknown feature `{}`", feature).emit();
970 // FIXME(#44232): the `used_features` table no longer exists, so we
971 // don't lint about unused features. We should re-enable this one day!
974 fn unnecessary_stable_feature_lint(tcx: TyCtxt<'_>, span: Span, feature: Symbol, since: Symbol) {
975 tcx.struct_span_lint_hir(lint::builtin::STABLE_FEATURES, hir::CRATE_HIR_ID, span, |lint| {
977 "the feature `{}` has been stable since {} and no longer requires \
978 an attribute to enable",
985 fn duplicate_feature_err(sess: &Session, span: Span, feature: Symbol) {
986 struct_span_err!(sess, span, E0636, "the feature `{}` has already been declared", feature)
990 fn missing_const_err(session: &Session, fn_sig_span: Span, const_span: Span) {
991 const ERROR_MSG: &'static str = "attributes `#[rustc_const_unstable]` \
992 and `#[rustc_const_stable]` require \
993 the function or method to be `const`";
996 .struct_span_err(fn_sig_span, ERROR_MSG)
997 .span_help(fn_sig_span, "make the function or method const")
998 .span_label(const_span, "attribute specified here")