1use std::num::NonZero;
5
6use rustc_ast_lowering::stability::extern_abi_stability;
7use rustc_data_structures::fx::FxIndexMap;
8use rustc_data_structures::unord::{ExtendUnord, UnordMap, UnordSet};
9use rustc_feature::{EnabledLangFeature, EnabledLibFeature};
10use rustc_hir::attrs::{AttributeKind, DeprecatedSince};
11use rustc_hir::def::{DefKind, Res};
12use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId, LocalModDefId};
13use rustc_hir::intravisit::{self, Visitor, VisitorExt};
14use rustc_hir::{
15 self as hir, AmbigArg, ConstStability, DefaultBodyStability, FieldDef, HirId, Item, ItemKind,
16 Path, Stability, StabilityLevel, StableSince, TraitRef, Ty, TyKind, UnstableReason, UsePath,
17 VERSION_PLACEHOLDER, Variant, find_attr,
18};
19use rustc_middle::hir::nested_filter;
20use rustc_middle::middle::lib_features::{FeatureStability, LibFeatures};
21use rustc_middle::middle::privacy::EffectiveVisibilities;
22use rustc_middle::middle::stability::{AllowUnstable, Deprecated, DeprecationEntry, EvalResult};
23use rustc_middle::query::{LocalCrate, Providers};
24use rustc_middle::ty::print::with_no_trimmed_paths;
25use rustc_middle::ty::{AssocContainer, TyCtxt};
26use rustc_session::lint;
27use rustc_session::lint::builtin::{DEPRECATED, INEFFECTIVE_UNSTABLE_TRAIT_IMPL};
28use rustc_span::{Span, Symbol, sym};
29use tracing::instrument;
30
31use crate::errors;
32
33#[derive(PartialEq)]
34enum AnnotationKind {
35 Required,
37 Prohibited,
39 DeprecationProhibited,
41 Container,
43}
44
45fn inherit_deprecation(def_kind: DefKind) -> bool {
46 match def_kind {
47 DefKind::LifetimeParam | DefKind::TyParam | DefKind::ConstParam => false,
48 _ => true,
49 }
50}
51
52fn inherit_const_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
53 let def_kind = tcx.def_kind(def_id);
54 match def_kind {
55 DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst => {
56 match tcx.def_kind(tcx.local_parent(def_id)) {
57 DefKind::Impl { of_trait: true } => true,
58 _ => false,
59 }
60 }
61 _ => false,
62 }
63}
64
65fn annotation_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> AnnotationKind {
66 let def_kind = tcx.def_kind(def_id);
67 match def_kind {
68 DefKind::Impl { of_trait: false } | DefKind::ForeignMod => AnnotationKind::Container,
73 DefKind::Impl { of_trait: true } => AnnotationKind::DeprecationProhibited,
74
75 DefKind::TyParam | DefKind::ConstParam => {
77 match &tcx.hir_node_by_def_id(def_id).expect_generic_param().kind {
78 hir::GenericParamKind::Type { default: Some(_), .. }
79 | hir::GenericParamKind::Const { default: Some(_), .. } => {
80 AnnotationKind::Container
81 }
82 _ => AnnotationKind::Prohibited,
83 }
84 }
85
86 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst => {
88 match tcx.def_kind(tcx.local_parent(def_id)) {
89 DefKind::Impl { of_trait: true } => AnnotationKind::Prohibited,
90 _ => AnnotationKind::Required,
91 }
92 }
93
94 _ => AnnotationKind::Required,
95 }
96}
97
98fn lookup_deprecation_entry(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<DeprecationEntry> {
99 let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id));
100 let depr = find_attr!(attrs,
101 AttributeKind::Deprecation { deprecation, span: _ } => *deprecation
102 );
103
104 let Some(depr) = depr else {
105 if inherit_deprecation(tcx.def_kind(def_id)) {
106 let parent_id = tcx.opt_local_parent(def_id)?;
107 let parent_depr = tcx.lookup_deprecation_entry(parent_id)?;
108 return Some(parent_depr);
109 }
110
111 return None;
112 };
113
114 Some(DeprecationEntry::local(depr, def_id))
116}
117
118fn inherit_stability(def_kind: DefKind) -> bool {
119 match def_kind {
120 DefKind::Field | DefKind::Variant | DefKind::Ctor(..) => true,
121 _ => false,
122 }
123}
124
125const FORCE_UNSTABLE: Stability = Stability {
132 level: StabilityLevel::Unstable {
133 reason: UnstableReason::Default,
134 issue: NonZero::new(27812),
135 is_soft: false,
136 implied_by: None,
137 old_name: None,
138 },
139 feature: sym::rustc_private,
140};
141
142#[instrument(level = "debug", skip(tcx))]
143fn lookup_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<Stability> {
144 if !tcx.features().staged_api() {
147 if !tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
148 return None;
149 }
150
151 let Some(parent) = tcx.opt_local_parent(def_id) else { return Some(FORCE_UNSTABLE) };
152
153 if inherit_deprecation(tcx.def_kind(def_id)) {
154 let parent = tcx.lookup_stability(parent)?;
155 if parent.is_unstable() {
156 return Some(parent);
157 }
158 }
159
160 return None;
161 }
162
163 let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id));
165 let stab = find_attr!(attrs, AttributeKind::Stability { stability, span: _ } => *stability);
166
167 if let Some(stab) = stab {
168 return Some(stab);
169 }
170
171 if inherit_deprecation(tcx.def_kind(def_id)) {
172 let Some(parent) = tcx.opt_local_parent(def_id) else {
173 return tcx
174 .sess
175 .opts
176 .unstable_opts
177 .force_unstable_if_unmarked
178 .then_some(FORCE_UNSTABLE);
179 };
180 let parent = tcx.lookup_stability(parent)?;
181 if parent.is_unstable() || inherit_stability(tcx.def_kind(def_id)) {
182 return Some(parent);
183 }
184 }
185
186 None
187}
188
189#[instrument(level = "debug", skip(tcx))]
190fn lookup_default_body_stability(
191 tcx: TyCtxt<'_>,
192 def_id: LocalDefId,
193) -> Option<DefaultBodyStability> {
194 if !tcx.features().staged_api() {
195 return None;
196 }
197
198 let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id));
199 find_attr!(attrs, AttributeKind::BodyStability { stability, .. } => *stability)
201}
202
203#[instrument(level = "debug", skip(tcx))]
204fn lookup_const_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ConstStability> {
205 if !tcx.features().staged_api() {
206 if inherit_deprecation(tcx.def_kind(def_id)) {
209 let parent = tcx.opt_local_parent(def_id)?;
210 let parent_stab = tcx.lookup_stability(parent)?;
211 if parent_stab.is_unstable()
212 && let Some(fn_sig) = tcx.hir_node_by_def_id(def_id).fn_sig()
213 && fn_sig.header.is_const()
214 {
215 let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id));
216 let const_stability_indirect =
217 find_attr!(attrs, AttributeKind::ConstStabilityIndirect);
218 return Some(ConstStability::unmarked(const_stability_indirect, parent_stab));
219 }
220 }
221
222 return None;
223 }
224
225 let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id));
226 let const_stability_indirect = find_attr!(attrs, AttributeKind::ConstStabilityIndirect);
227 let const_stab =
228 find_attr!(attrs, AttributeKind::ConstStability { stability, span: _ } => *stability);
229
230 let mut const_stab = const_stab
233 .map(|const_stab| ConstStability::from_partial(const_stab, const_stability_indirect));
234
235 if let Some(fn_sig) = tcx.hir_node_by_def_id(def_id).fn_sig()
238 && fn_sig.header.is_const()
239 && const_stab.is_none()
240 && let Some(inherit_regular_stab) = tcx.lookup_stability(def_id)
242 && inherit_regular_stab.is_unstable()
243 {
244 const_stab = Some(ConstStability {
245 const_stable_indirect: true,
247 promotable: false,
248 level: inherit_regular_stab.level,
249 feature: inherit_regular_stab.feature,
250 });
251 }
252
253 if let Some(const_stab) = const_stab {
254 return Some(const_stab);
255 }
256
257 if inherit_const_stability(tcx, def_id) {
261 let parent = tcx.opt_local_parent(def_id)?;
262 let parent = tcx.lookup_const_stability(parent)?;
263 if parent.is_const_unstable() {
264 return Some(parent);
265 }
266 }
267
268 None
269}
270
271fn stability_implications(tcx: TyCtxt<'_>, LocalCrate: LocalCrate) -> UnordMap<Symbol, Symbol> {
272 let mut implications = UnordMap::default();
273
274 let mut register_implication = |def_id| {
275 if let Some(stability) = tcx.lookup_stability(def_id)
276 && let StabilityLevel::Unstable { implied_by: Some(implied_by), .. } = stability.level
277 {
278 implications.insert(implied_by, stability.feature);
279 }
280
281 if let Some(stability) = tcx.lookup_const_stability(def_id)
282 && let StabilityLevel::Unstable { implied_by: Some(implied_by), .. } = stability.level
283 {
284 implications.insert(implied_by, stability.feature);
285 }
286 };
287
288 if tcx.features().staged_api() {
289 register_implication(CRATE_DEF_ID);
290 for def_id in tcx.hir_crate_items(()).definitions() {
291 register_implication(def_id);
292 let def_kind = tcx.def_kind(def_id);
293 if def_kind.is_adt() {
294 let adt = tcx.adt_def(def_id);
295 for variant in adt.variants() {
296 if variant.def_id != def_id.to_def_id() {
297 register_implication(variant.def_id.expect_local());
298 }
299 for field in &variant.fields {
300 register_implication(field.did.expect_local());
301 }
302 if let Some(ctor_def_id) = variant.ctor_def_id() {
303 register_implication(ctor_def_id.expect_local())
304 }
305 }
306 }
307 if def_kind.has_generics() {
308 for param in tcx.generics_of(def_id).own_params.iter() {
309 register_implication(param.def_id.expect_local())
310 }
311 }
312 }
313 }
314
315 implications
316}
317
318struct MissingStabilityAnnotations<'tcx> {
319 tcx: TyCtxt<'tcx>,
320 effective_visibilities: &'tcx EffectiveVisibilities,
321}
322
323impl<'tcx> MissingStabilityAnnotations<'tcx> {
324 #[instrument(level = "trace", skip(self))]
326 fn check_compatible_stability(&self, def_id: LocalDefId) {
327 if !self.tcx.features().staged_api() {
328 return;
329 }
330
331 let depr = self.tcx.lookup_deprecation_entry(def_id);
332 let stab = self.tcx.lookup_stability(def_id);
333 let const_stab = self.tcx.lookup_const_stability(def_id);
334
335 macro_rules! find_attr_span {
336 ($name:ident) => {{
337 let attrs = self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id));
338 find_attr!(attrs, AttributeKind::$name { span, .. } => *span)
339 }}
340 }
341
342 if stab.is_none()
343 && depr.map_or(false, |d| d.attr.is_since_rustc_version())
344 && let Some(span) = find_attr_span!(Deprecation)
345 {
346 self.tcx.dcx().emit_err(errors::DeprecatedAttribute { span });
347 }
348
349 if let Some(stab) = stab {
350 let kind = annotation_kind(self.tcx, def_id);
352 if kind == AnnotationKind::Prohibited
353 || (kind == AnnotationKind::Container && stab.level.is_stable() && depr.is_some())
354 {
355 if let Some(span) = find_attr_span!(Stability) {
356 let item_sp = self.tcx.def_span(def_id);
357 self.tcx.dcx().emit_err(errors::UselessStability { span, item_sp });
358 }
359 }
360
361 if let Some(depr) = depr
364 && let DeprecatedSince::RustcVersion(dep_since) = depr.attr.since
365 && let StabilityLevel::Stable { since: stab_since, .. } = stab.level
366 && let Some(span) = find_attr_span!(Stability)
367 {
368 let item_sp = self.tcx.def_span(def_id);
369 match stab_since {
370 StableSince::Current => {
371 self.tcx
372 .dcx()
373 .emit_err(errors::CannotStabilizeDeprecated { span, item_sp });
374 }
375 StableSince::Version(stab_since) => {
376 if dep_since < stab_since {
377 self.tcx
378 .dcx()
379 .emit_err(errors::CannotStabilizeDeprecated { span, item_sp });
380 }
381 }
382 StableSince::Err(_) => {
383 }
386 }
387 }
388 }
389
390 let fn_sig = self.tcx.hir_node_by_def_id(def_id).fn_sig();
393 if let Some(fn_sig) = fn_sig
394 && !fn_sig.header.is_const()
395 && const_stab.is_some()
396 && find_attr_span!(ConstStability).is_some()
397 {
398 self.tcx.dcx().emit_err(errors::MissingConstErr { fn_sig_span: fn_sig.span });
399 }
400
401 if let Some(const_stab) = const_stab
403 && let Some(fn_sig) = fn_sig
404 && const_stab.is_const_stable()
405 && !stab.is_some_and(|s| s.is_stable())
406 && let Some(const_span) = find_attr_span!(ConstStability)
407 {
408 self.tcx
409 .dcx()
410 .emit_err(errors::ConstStableNotStable { fn_sig_span: fn_sig.span, const_span });
411 }
412
413 if let Some(stab) = &const_stab
414 && stab.is_const_stable()
415 && stab.const_stable_indirect
416 && let Some(span) = find_attr_span!(ConstStability)
417 {
418 self.tcx.dcx().emit_err(errors::RustcConstStableIndirectPairing { span });
419 }
420 }
421
422 #[instrument(level = "debug", skip(self))]
423 fn check_missing_stability(&self, def_id: LocalDefId) {
424 let stab = self.tcx.lookup_stability(def_id);
425 self.tcx.ensure_ok().lookup_const_stability(def_id);
426 if !self.tcx.sess.is_test_crate()
427 && stab.is_none()
428 && self.effective_visibilities.is_reachable(def_id)
429 {
430 let descr = self.tcx.def_descr(def_id.to_def_id());
431 let span = self.tcx.def_span(def_id);
432 self.tcx.dcx().emit_err(errors::MissingStabilityAttr { span, descr });
433 }
434 }
435
436 fn check_missing_const_stability(&self, def_id: LocalDefId) {
437 let is_const = self.tcx.is_const_fn(def_id.to_def_id())
438 || (self.tcx.def_kind(def_id.to_def_id()) == DefKind::Trait
439 && self.tcx.is_const_trait(def_id.to_def_id()));
440
441 if is_const
443 && self.effective_visibilities.is_reachable(def_id)
444 && self.tcx.lookup_const_stability(def_id).is_none()
445 {
446 let span = self.tcx.def_span(def_id);
447 let descr = self.tcx.def_descr(def_id.to_def_id());
448 self.tcx.dcx().emit_err(errors::MissingConstStabAttr { span, descr });
449 }
450 }
451}
452
453impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> {
454 type NestedFilter = nested_filter::OnlyBodies;
455
456 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
457 self.tcx
458 }
459
460 fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
461 self.check_compatible_stability(i.owner_id.def_id);
462
463 if !matches!(
468 i.kind,
469 hir::ItemKind::Impl(hir::Impl { of_trait: None, .. })
470 | hir::ItemKind::ForeignMod { .. }
471 ) {
472 self.check_missing_stability(i.owner_id.def_id);
473 }
474
475 self.check_missing_const_stability(i.owner_id.def_id);
477
478 intravisit::walk_item(self, i)
479 }
480
481 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
482 self.check_compatible_stability(ti.owner_id.def_id);
483 self.check_missing_stability(ti.owner_id.def_id);
484 intravisit::walk_trait_item(self, ti);
485 }
486
487 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
488 self.check_compatible_stability(ii.owner_id.def_id);
489 if let hir::ImplItemImplKind::Inherent { .. } = ii.impl_kind {
490 self.check_missing_stability(ii.owner_id.def_id);
491 self.check_missing_const_stability(ii.owner_id.def_id);
492 }
493 intravisit::walk_impl_item(self, ii);
494 }
495
496 fn visit_variant(&mut self, var: &'tcx Variant<'tcx>) {
497 self.check_compatible_stability(var.def_id);
498 self.check_missing_stability(var.def_id);
499 if let Some(ctor_def_id) = var.data.ctor_def_id() {
500 self.check_missing_stability(ctor_def_id);
501 }
502 intravisit::walk_variant(self, var);
503 }
504
505 fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) {
506 self.check_compatible_stability(s.def_id);
507 self.check_missing_stability(s.def_id);
508 intravisit::walk_field_def(self, s);
509 }
510
511 fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) {
512 self.check_compatible_stability(i.owner_id.def_id);
513 self.check_missing_stability(i.owner_id.def_id);
514 intravisit::walk_foreign_item(self, i);
515 }
516
517 fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
518 self.check_compatible_stability(p.def_id);
519 intravisit::walk_generic_param(self, p);
523 }
524}
525
526fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
529 tcx.hir_visit_item_likes_in_module(module_def_id, &mut Checker { tcx });
530
531 let is_staged_api =
532 tcx.sess.opts.unstable_opts.force_unstable_if_unmarked || tcx.features().staged_api();
533 if is_staged_api {
534 let effective_visibilities = &tcx.effective_visibilities(());
535 let mut missing = MissingStabilityAnnotations { tcx, effective_visibilities };
536 if module_def_id.is_top_level_module() {
537 missing.check_missing_stability(CRATE_DEF_ID);
538 }
539 tcx.hir_visit_item_likes_in_module(module_def_id, &mut missing);
540 }
541
542 if module_def_id.is_top_level_module() {
543 check_unused_or_stable_features(tcx)
544 }
545}
546
547pub(crate) fn provide(providers: &mut Providers) {
548 *providers = Providers {
549 check_mod_unstable_api_usage,
550 stability_implications,
551 lookup_stability,
552 lookup_const_stability,
553 lookup_default_body_stability,
554 lookup_deprecation_entry,
555 ..*providers
556 };
557}
558
559struct Checker<'tcx> {
560 tcx: TyCtxt<'tcx>,
561}
562
563impl<'tcx> Visitor<'tcx> for Checker<'tcx> {
564 type NestedFilter = nested_filter::OnlyBodies;
565
566 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
570 self.tcx
571 }
572
573 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
574 match item.kind {
575 hir::ItemKind::ExternCrate(_, ident) => {
576 if item.span.is_dummy() && ident.name != sym::std {
579 return;
580 }
581
582 let Some(cnum) = self.tcx.extern_mod_stmt_cnum(item.owner_id.def_id) else {
583 return;
584 };
585 let def_id = cnum.as_def_id();
586 self.tcx.check_stability(def_id, Some(item.hir_id()), item.span, None);
587 }
588
589 hir::ItemKind::Impl(hir::Impl {
593 of_trait: Some(of_trait),
594 self_ty,
595 items,
596 constness,
597 ..
598 }) => {
599 let features = self.tcx.features();
600 if features.staged_api() {
601 let attrs = self.tcx.hir_attrs(item.hir_id());
602 let stab = find_attr!(attrs, AttributeKind::Stability{stability, span} => (*stability, *span));
603
604 let const_stab = find_attr!(attrs, AttributeKind::ConstStability{stability, ..} => *stability);
606
607 let unstable_feature_stab =
608 find_attr!(attrs, AttributeKind::UnstableFeatureBound(i) => i)
609 .map(|i| i.as_slice())
610 .unwrap_or_default();
611
612 if let Some((
628 Stability { level: StabilityLevel::Unstable { .. }, feature },
629 span,
630 )) = stab
631 {
632 let mut c = CheckTraitImplStable { tcx: self.tcx, fully_stable: true };
633 c.visit_ty_unambig(self_ty);
634 c.visit_trait_ref(&of_trait.trait_ref);
635
636 let mut unstable_feature_bound_in_effect = false;
639 for (unstable_bound_feat_name, _) in unstable_feature_stab {
640 if *unstable_bound_feat_name == feature {
641 unstable_feature_bound_in_effect = true;
642 }
643 }
644
645 if of_trait.trait_ref.path.res != Res::Err
648 && c.fully_stable
649 && !unstable_feature_bound_in_effect
650 {
651 self.tcx.emit_node_span_lint(
652 INEFFECTIVE_UNSTABLE_TRAIT_IMPL,
653 item.hir_id(),
654 span,
655 errors::IneffectiveUnstableImpl,
656 );
657 }
658 }
659
660 if features.const_trait_impl()
661 && let hir::Constness::Const = constness
662 {
663 let stable_or_implied_stable = match const_stab {
664 None => true,
665 Some(stab) if stab.is_const_stable() => {
666 self.tcx
670 .dcx()
671 .emit_err(errors::TraitImplConstStable { span: item.span });
672 true
673 }
674 Some(_) => false,
675 };
676
677 if let Some(trait_id) = of_trait.trait_ref.trait_def_id()
678 && let Some(const_stab) = self.tcx.lookup_const_stability(trait_id)
679 {
680 if const_stab.is_const_stable() != stable_or_implied_stable {
682 let trait_span = self.tcx.def_ident_span(trait_id).unwrap();
683
684 let impl_stability = if stable_or_implied_stable {
685 errors::ImplConstStability::Stable { span: item.span }
686 } else {
687 errors::ImplConstStability::Unstable { span: item.span }
688 };
689 let trait_stability = if const_stab.is_const_stable() {
690 errors::TraitConstStability::Stable { span: trait_span }
691 } else {
692 errors::TraitConstStability::Unstable { span: trait_span }
693 };
694
695 self.tcx.dcx().emit_err(errors::TraitImplConstStabilityMismatch {
696 span: item.span,
697 impl_stability,
698 trait_stability,
699 });
700 }
701 }
702 }
703 }
704
705 if let hir::Constness::Const = constness
706 && let Some(def_id) = of_trait.trait_ref.trait_def_id()
707 {
708 self.tcx.check_const_stability(
710 def_id,
711 of_trait.trait_ref.path.span,
712 of_trait.trait_ref.path.span,
713 );
714 }
715
716 for impl_item_ref in items {
717 let impl_item = self.tcx.associated_item(impl_item_ref.owner_id);
718
719 if let AssocContainer::TraitImpl(Ok(def_id)) = impl_item.container {
720 self.tcx.check_stability(
722 def_id,
723 None,
724 self.tcx.def_span(impl_item_ref.owner_id),
725 None,
726 );
727 }
728 }
729 }
730
731 _ => (),
732 }
733 intravisit::walk_item(self, item);
734 }
735
736 fn visit_poly_trait_ref(&mut self, t: &'tcx hir::PolyTraitRef<'tcx>) {
737 match t.modifiers.constness {
738 hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) => {
739 if let Some(def_id) = t.trait_ref.trait_def_id() {
740 self.tcx.check_const_stability(def_id, t.trait_ref.path.span, span);
741 }
742 }
743 hir::BoundConstness::Never => {}
744 }
745 intravisit::walk_poly_trait_ref(self, t);
746 }
747
748 fn visit_use(&mut self, path: &'tcx UsePath<'tcx>, hir_id: HirId) {
749 let res = path.res;
750
751 if let Some(ty_ns_res) = res.type_ns
755 && let Some(value_ns_res) = res.value_ns
756 && let Some(type_ns_did) = ty_ns_res.opt_def_id()
757 && let Some(value_ns_did) = value_ns_res.opt_def_id()
758 && let DefKind::Ctor(.., _) = self.tcx.def_kind(value_ns_did)
759 && self.tcx.parent(value_ns_did) == type_ns_did
760 {
761 let UsePath { segments, res: _, span } = *path;
764 self.visit_path(&Path { segments, res: value_ns_res, span }, hir_id);
765
766 if let Some(res) = res.macro_ns {
769 self.visit_path(&Path { segments, res, span }, hir_id);
770 }
771 } else {
772 intravisit::walk_use(self, path, hir_id)
774 }
775 }
776
777 fn visit_path(&mut self, path: &hir::Path<'tcx>, id: hir::HirId) {
778 if let Some(def_id) = path.res.opt_def_id() {
779 let method_span = path.segments.last().map(|s| s.ident.span);
780 let item_is_allowed = self.tcx.check_stability_allow_unstable(
781 def_id,
782 Some(id),
783 path.span,
784 method_span,
785 if is_unstable_reexport(self.tcx, id) {
786 AllowUnstable::Yes
787 } else {
788 AllowUnstable::No
789 },
790 );
791
792 if item_is_allowed {
793 let is_allowed_through_unstable_modules: Option<Symbol> =
795 self.tcx.lookup_stability(def_id).and_then(|stab| match stab.level {
796 StabilityLevel::Stable { allowed_through_unstable_modules, .. } => {
797 allowed_through_unstable_modules
798 }
799 _ => None,
800 });
801
802 let parents = path.segments.iter().rev().skip(1);
814 for path_segment in parents {
815 if let Some(def_id) = path_segment.res.opt_def_id() {
816 match is_allowed_through_unstable_modules {
817 None => {
818 self.tcx.check_stability_allow_unstable(
822 def_id,
823 None,
824 path.span,
825 None,
826 if is_unstable_reexport(self.tcx, id) {
827 AllowUnstable::Yes
828 } else {
829 AllowUnstable::No
830 },
831 );
832 }
833 Some(deprecation) => {
834 let eval_result = self.tcx.eval_stability_allow_unstable(
837 def_id,
838 None,
839 path.span,
840 None,
841 if is_unstable_reexport(self.tcx, id) {
842 AllowUnstable::Yes
843 } else {
844 AllowUnstable::No
845 },
846 );
847 let is_allowed = matches!(eval_result, EvalResult::Allow);
848 if !is_allowed {
849 if self.tcx.lint_level_at_node(DEPRECATED, id).level
853 == lint::Level::Allow
854 {
855 return;
856 }
857 let def_path =
859 with_no_trimmed_paths!(self.tcx.def_path_str(def_id));
860 let def_kind = self.tcx.def_descr(def_id);
861 let diag = Deprecated {
862 sub: None,
863 kind: def_kind.to_owned(),
864 path: def_path,
865 note: Some(deprecation),
866 since_kind: lint::DeprecatedSinceKind::InEffect,
867 };
868 self.tcx.emit_node_span_lint(
869 DEPRECATED,
870 id,
871 method_span.unwrap_or(path.span),
872 diag,
873 );
874 }
875 }
876 }
877 }
878 }
879 }
880 }
881
882 intravisit::walk_path(self, path)
883 }
884}
885
886fn is_unstable_reexport(tcx: TyCtxt<'_>, id: hir::HirId) -> bool {
890 let Some(owner) = id.as_owner() else {
892 return false;
893 };
894 let def_id = owner.def_id;
895
896 let Some(stab) = tcx.lookup_stability(def_id) else {
897 return false;
898 };
899
900 if stab.level.is_stable() {
901 return false;
903 }
904
905 if !matches!(tcx.hir_expect_item(def_id).kind, ItemKind::Use(..)) {
907 return false;
908 }
909
910 true
911}
912
913struct CheckTraitImplStable<'tcx> {
914 tcx: TyCtxt<'tcx>,
915 fully_stable: bool,
916}
917
918impl<'tcx> Visitor<'tcx> for CheckTraitImplStable<'tcx> {
919 fn visit_path(&mut self, path: &hir::Path<'tcx>, _id: hir::HirId) {
920 if let Some(def_id) = path.res.opt_def_id()
921 && let Some(stab) = self.tcx.lookup_stability(def_id)
922 {
923 self.fully_stable &= stab.level.is_stable();
924 }
925 intravisit::walk_path(self, path)
926 }
927
928 fn visit_trait_ref(&mut self, t: &'tcx TraitRef<'tcx>) {
929 if let Res::Def(DefKind::Trait, trait_did) = t.path.res {
930 if let Some(stab) = self.tcx.lookup_stability(trait_did) {
931 self.fully_stable &= stab.level.is_stable();
932 }
933 }
934 intravisit::walk_trait_ref(self, t)
935 }
936
937 fn visit_ty(&mut self, t: &'tcx Ty<'tcx, AmbigArg>) {
938 if let TyKind::Never = t.kind {
939 self.fully_stable = false;
940 }
941 if let TyKind::FnPtr(function) = t.kind {
942 if extern_abi_stability(function.abi).is_err() {
943 self.fully_stable = false;
944 }
945 }
946 intravisit::walk_ty(self, t)
947 }
948
949 fn visit_fn_decl(&mut self, fd: &'tcx hir::FnDecl<'tcx>) {
950 for ty in fd.inputs {
951 self.visit_ty_unambig(ty)
952 }
953 if let hir::FnRetTy::Return(output_ty) = fd.output {
954 match output_ty.kind {
955 TyKind::Never => {} _ => self.visit_ty_unambig(output_ty),
957 }
958 }
959 }
960}
961
962pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) {
967 let _prof_timer = tcx.sess.timer("unused_lib_feature_checking");
968
969 let enabled_lang_features = tcx.features().enabled_lang_features();
970 let mut lang_features = UnordSet::default();
971 for EnabledLangFeature { gate_name, attr_sp, stable_since } in enabled_lang_features {
972 if let Some(version) = stable_since {
973 unnecessary_stable_feature_lint(tcx, *attr_sp, *gate_name, *version);
975 }
976 if !lang_features.insert(gate_name) {
977 tcx.dcx().emit_err(errors::DuplicateFeatureErr { span: *attr_sp, feature: *gate_name });
979 }
980 }
981
982 let enabled_lib_features = tcx.features().enabled_lib_features();
983 let mut remaining_lib_features = FxIndexMap::default();
984 for EnabledLibFeature { gate_name, attr_sp } in enabled_lib_features {
985 if remaining_lib_features.contains_key(gate_name) {
986 tcx.dcx().emit_err(errors::DuplicateFeatureErr { span: *attr_sp, feature: *gate_name });
988 }
989 remaining_lib_features.insert(*gate_name, *attr_sp);
990 }
991 remaining_lib_features.swap_remove(&sym::libc);
999 remaining_lib_features.swap_remove(&sym::test);
1000
1001 fn check_features<'tcx>(
1020 tcx: TyCtxt<'tcx>,
1021 remaining_lib_features: &mut FxIndexMap<Symbol, Span>,
1022 remaining_implications: &mut UnordMap<Symbol, Symbol>,
1023 defined_features: &LibFeatures,
1024 all_implications: &UnordMap<Symbol, Symbol>,
1025 ) {
1026 for (feature, stability) in defined_features.to_sorted_vec() {
1027 if let FeatureStability::AcceptedSince(since) = stability
1028 && let Some(span) = remaining_lib_features.get(&feature)
1029 {
1030 if let Some(implies) = all_implications.get(&feature) {
1032 unnecessary_partially_stable_feature_lint(tcx, *span, feature, *implies, since);
1033 } else {
1034 unnecessary_stable_feature_lint(tcx, *span, feature, since);
1035 }
1036 }
1037 remaining_lib_features.swap_remove(&feature);
1039
1040 remaining_implications.remove(&feature);
1045
1046 if let FeatureStability::Unstable { old_name: Some(alias) } = stability
1047 && let Some(span) = remaining_lib_features.swap_remove(&alias)
1048 {
1049 tcx.dcx().emit_err(errors::RenamedFeature { span, feature, alias });
1050 }
1051
1052 if remaining_lib_features.is_empty() && remaining_implications.is_empty() {
1053 break;
1054 }
1055 }
1056 }
1057
1058 let mut remaining_implications = tcx.stability_implications(LOCAL_CRATE).clone();
1060
1061 let local_defined_features = tcx.lib_features(LOCAL_CRATE);
1064 if !remaining_lib_features.is_empty() || !remaining_implications.is_empty() {
1065 let mut all_implications = remaining_implications.clone();
1069 for &cnum in tcx.crates(()) {
1070 all_implications
1071 .extend_unord(tcx.stability_implications(cnum).items().map(|(k, v)| (*k, *v)));
1072 }
1073
1074 check_features(
1075 tcx,
1076 &mut remaining_lib_features,
1077 &mut remaining_implications,
1078 local_defined_features,
1079 &all_implications,
1080 );
1081
1082 for &cnum in tcx.crates(()) {
1083 if remaining_lib_features.is_empty() && remaining_implications.is_empty() {
1084 break;
1085 }
1086 check_features(
1087 tcx,
1088 &mut remaining_lib_features,
1089 &mut remaining_implications,
1090 tcx.lib_features(cnum),
1091 &all_implications,
1092 );
1093 }
1094 }
1095
1096 for (feature, span) in remaining_lib_features {
1097 tcx.dcx().emit_err(errors::UnknownFeature { span, feature });
1098 }
1099
1100 for (&implied_by, &feature) in remaining_implications.to_sorted_stable_ord() {
1101 let local_defined_features = tcx.lib_features(LOCAL_CRATE);
1102 let span = local_defined_features
1103 .stability
1104 .get(&feature)
1105 .expect("feature that implied another does not exist")
1106 .1;
1107 tcx.dcx().emit_err(errors::ImpliedFeatureNotExist { span, feature, implied_by });
1108 }
1109
1110 }
1113
1114fn unnecessary_partially_stable_feature_lint(
1115 tcx: TyCtxt<'_>,
1116 span: Span,
1117 feature: Symbol,
1118 implies: Symbol,
1119 since: Symbol,
1120) {
1121 tcx.emit_node_span_lint(
1122 lint::builtin::STABLE_FEATURES,
1123 hir::CRATE_HIR_ID,
1124 span,
1125 errors::UnnecessaryPartialStableFeature {
1126 span,
1127 line: tcx.sess.source_map().span_extend_to_line(span),
1128 feature,
1129 since,
1130 implies,
1131 },
1132 );
1133}
1134
1135fn unnecessary_stable_feature_lint(
1136 tcx: TyCtxt<'_>,
1137 span: Span,
1138 feature: Symbol,
1139 mut since: Symbol,
1140) {
1141 if since.as_str() == VERSION_PLACEHOLDER {
1142 since = sym::env_CFG_RELEASE;
1143 }
1144 tcx.emit_node_span_lint(
1145 lint::builtin::STABLE_FEATURES,
1146 hir::CRATE_HIR_ID,
1147 span,
1148 errors::UnnecessaryStableFeature { feature, since },
1149 );
1150}