1#![allow(internal_features)]
3#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
4#![doc(rust_logo)]
5#![feature(associated_type_defaults)]
6#![feature(rustdoc_internals)]
7#![feature(try_blocks)]
8mod errors;
11
12use std::fmt;
13use std::marker::PhantomData;
14use std::ops::ControlFlow;
15
16use errors::{
17 FieldIsPrivate, FieldIsPrivateLabel, FromPrivateDependencyInPublicInterface, InPublicInterface,
18 ItemIsPrivate, PrivateInterfacesOrBoundsLint, ReportEffectiveVisibility, UnnameableTypesLint,
19 UnnamedItemIsPrivate,
20};
21use rustc_ast::MacroDef;
22use rustc_ast::visit::{VisitorResult, try_visit};
23use rustc_data_structures::fx::FxHashSet;
24use rustc_data_structures::intern::Interned;
25use rustc_errors::{MultiSpan, listify};
26use rustc_hir as hir;
27use rustc_hir::attrs::AttributeKind;
28use rustc_hir::def::{DefKind, Res};
29use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId};
30use rustc_hir::intravisit::{self, InferKind, Visitor};
31use rustc_hir::{AmbigArg, ForeignItemId, ItemId, OwnerId, PatKind, find_attr};
32use rustc_middle::middle::privacy::{EffectiveVisibilities, EffectiveVisibility, Level};
33use rustc_middle::query::Providers;
34use rustc_middle::ty::print::PrintTraitRefExt as _;
35use rustc_middle::ty::{
36 self, Const, GenericParamDefKind, TraitRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
37 TypeVisitor,
38};
39use rustc_middle::{bug, span_bug};
40use rustc_session::lint;
41use rustc_span::hygiene::Transparency;
42use rustc_span::{Ident, Span, Symbol, sym};
43use tracing::debug;
44
45rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
46
47struct LazyDefPathStr<'tcx> {
52 def_id: DefId,
53 tcx: TyCtxt<'tcx>,
54}
55
56impl<'tcx> fmt::Display for LazyDefPathStr<'tcx> {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 write!(f, "{}", self.tcx.def_path_str(self.def_id))
59 }
60}
61
62pub trait DefIdVisitor<'tcx> {
71 type Result: VisitorResult = ();
72 const SHALLOW: bool = false;
73 fn skip_assoc_tys(&self) -> bool {
74 false
75 }
76
77 fn tcx(&self) -> TyCtxt<'tcx>;
78 fn visit_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display)
79 -> Self::Result;
80
81 fn skeleton(&mut self) -> DefIdVisitorSkeleton<'_, 'tcx, Self> {
83 DefIdVisitorSkeleton {
84 def_id_visitor: self,
85 visited_opaque_tys: Default::default(),
86 dummy: Default::default(),
87 }
88 }
89 fn visit(&mut self, ty_fragment: impl TypeVisitable<TyCtxt<'tcx>>) -> Self::Result {
90 ty_fragment.visit_with(&mut self.skeleton())
91 }
92 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> Self::Result {
93 self.skeleton().visit_trait(trait_ref)
94 }
95 fn visit_predicates(&mut self, predicates: ty::GenericPredicates<'tcx>) -> Self::Result {
96 self.skeleton().visit_clauses(predicates.predicates)
97 }
98 fn visit_clauses(&mut self, clauses: &[(ty::Clause<'tcx>, Span)]) -> Self::Result {
99 self.skeleton().visit_clauses(clauses)
100 }
101}
102
103pub struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> {
104 def_id_visitor: &'v mut V,
105 visited_opaque_tys: FxHashSet<DefId>,
106 dummy: PhantomData<TyCtxt<'tcx>>,
107}
108
109impl<'tcx, V> DefIdVisitorSkeleton<'_, 'tcx, V>
110where
111 V: DefIdVisitor<'tcx> + ?Sized,
112{
113 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> V::Result {
114 let TraitRef { def_id, args, .. } = trait_ref;
115 try_visit!(self.def_id_visitor.visit_def_id(
116 def_id,
117 "trait",
118 &trait_ref.print_only_trait_path()
119 ));
120 if V::SHALLOW { V::Result::output() } else { args.visit_with(self) }
121 }
122
123 fn visit_projection_term(&mut self, projection: ty::AliasTerm<'tcx>) -> V::Result {
124 let tcx = self.def_id_visitor.tcx();
125 let (trait_ref, assoc_args) = projection.trait_ref_and_own_args(tcx);
126 try_visit!(self.visit_trait(trait_ref));
127 if V::SHALLOW {
128 V::Result::output()
129 } else {
130 V::Result::from_branch(
131 assoc_args.iter().try_for_each(|arg| arg.visit_with(self).branch()),
132 )
133 }
134 }
135
136 fn visit_clause(&mut self, clause: ty::Clause<'tcx>) -> V::Result {
137 match clause.kind().skip_binder() {
138 ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity: _ }) => {
139 self.visit_trait(trait_ref)
140 }
141 ty::ClauseKind::HostEffect(pred) => {
142 try_visit!(self.visit_trait(pred.trait_ref));
143 pred.constness.visit_with(self)
144 }
145 ty::ClauseKind::Projection(ty::ProjectionPredicate {
146 projection_term: projection_ty,
147 term,
148 }) => {
149 try_visit!(term.visit_with(self));
150 self.visit_projection_term(projection_ty)
151 }
152 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _region)) => ty.visit_with(self),
153 ty::ClauseKind::RegionOutlives(..) => V::Result::output(),
154 ty::ClauseKind::ConstArgHasType(ct, ty) => {
155 try_visit!(ct.visit_with(self));
156 ty.visit_with(self)
157 }
158 ty::ClauseKind::ConstEvaluatable(ct) => ct.visit_with(self),
159 ty::ClauseKind::WellFormed(term) => term.visit_with(self),
160 ty::ClauseKind::UnstableFeature(_) => V::Result::output(),
161 }
162 }
163
164 fn visit_clauses(&mut self, clauses: &[(ty::Clause<'tcx>, Span)]) -> V::Result {
165 for &(clause, _) in clauses {
166 try_visit!(self.visit_clause(clause));
167 }
168 V::Result::output()
169 }
170}
171
172impl<'tcx, V> TypeVisitor<TyCtxt<'tcx>> for DefIdVisitorSkeleton<'_, 'tcx, V>
173where
174 V: DefIdVisitor<'tcx> + ?Sized,
175{
176 type Result = V::Result;
177
178 fn visit_predicate(&mut self, p: ty::Predicate<'tcx>) -> Self::Result {
179 self.visit_clause(p.as_clause().unwrap())
180 }
181
182 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
183 let tcx = self.def_id_visitor.tcx();
184 match *ty.kind() {
187 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), ..)
188 | ty::Foreign(def_id)
189 | ty::FnDef(def_id, ..)
190 | ty::Closure(def_id, ..)
191 | ty::CoroutineClosure(def_id, ..)
192 | ty::Coroutine(def_id, ..) => {
193 try_visit!(self.def_id_visitor.visit_def_id(def_id, "type", &ty));
194 if V::SHALLOW {
195 return V::Result::output();
196 }
197 if let ty::FnDef(..) = ty.kind() {
201 try_visit!(tcx.fn_sig(def_id).instantiate_identity().visit_with(self));
203 }
204 if let Some(assoc_item) = tcx.opt_associated_item(def_id)
209 && let Some(impl_def_id) = assoc_item.impl_container(tcx)
210 {
211 try_visit!(tcx.type_of(impl_def_id).instantiate_identity().visit_with(self));
212 }
213 }
214 ty::Alias(kind @ (ty::Inherent | ty::Free | ty::Projection), data) => {
215 if self.def_id_visitor.skip_assoc_tys() {
216 return V::Result::output();
222 }
223
224 try_visit!(self.def_id_visitor.visit_def_id(
225 data.def_id,
226 match kind {
227 ty::Inherent | ty::Projection => "associated type",
228 ty::Free => "type alias",
229 ty::Opaque => unreachable!(),
230 },
231 &LazyDefPathStr { def_id: data.def_id, tcx },
232 ));
233
234 return if V::SHALLOW {
236 V::Result::output()
237 } else if kind == ty::Projection {
238 self.visit_projection_term(data.into())
239 } else {
240 V::Result::from_branch(
241 data.args.iter().try_for_each(|arg| arg.visit_with(self).branch()),
242 )
243 };
244 }
245 ty::Dynamic(predicates, ..) => {
246 for predicate in predicates {
249 let trait_ref = match predicate.skip_binder() {
250 ty::ExistentialPredicate::Trait(trait_ref) => trait_ref,
251 ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx),
252 ty::ExistentialPredicate::AutoTrait(def_id) => {
253 ty::ExistentialTraitRef::new(tcx, def_id, ty::GenericArgs::empty())
254 }
255 };
256 let ty::ExistentialTraitRef { def_id, .. } = trait_ref;
257 try_visit!(self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref));
258 }
259 }
260 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
261 if self.visited_opaque_tys.insert(def_id) {
263 try_visit!(self.visit_clauses(tcx.explicit_item_bounds(def_id).skip_binder()));
271 }
272 }
273 ty::Bool
276 | ty::Char
277 | ty::Int(..)
278 | ty::Uint(..)
279 | ty::Float(..)
280 | ty::Str
281 | ty::Never
282 | ty::Array(..)
283 | ty::Slice(..)
284 | ty::Tuple(..)
285 | ty::RawPtr(..)
286 | ty::Ref(..)
287 | ty::Pat(..)
288 | ty::FnPtr(..)
289 | ty::UnsafeBinder(_)
290 | ty::Param(..)
291 | ty::Bound(..)
292 | ty::Error(_)
293 | ty::CoroutineWitness(..) => {}
294 ty::Placeholder(..) | ty::Infer(..) => {
295 bug!("unexpected type: {:?}", ty)
296 }
297 }
298
299 if V::SHALLOW { V::Result::output() } else { ty.super_visit_with(self) }
300 }
301
302 fn visit_const(&mut self, c: Const<'tcx>) -> Self::Result {
303 let tcx = self.def_id_visitor.tcx();
304 tcx.expand_abstract_consts(c).super_visit_with(self)
305 }
306}
307
308fn min(vis1: ty::Visibility, vis2: ty::Visibility, tcx: TyCtxt<'_>) -> ty::Visibility {
309 if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
310}
311
312struct FindMin<'a, 'tcx, VL: VisibilityLike, const SHALLOW: bool> {
317 tcx: TyCtxt<'tcx>,
318 effective_visibilities: &'a EffectiveVisibilities,
319 min: VL,
320}
321
322impl<'a, 'tcx, VL: VisibilityLike, const SHALLOW: bool> DefIdVisitor<'tcx>
323 for FindMin<'a, 'tcx, VL, SHALLOW>
324{
325 const SHALLOW: bool = SHALLOW;
326 fn skip_assoc_tys(&self) -> bool {
327 true
328 }
329 fn tcx(&self) -> TyCtxt<'tcx> {
330 self.tcx
331 }
332 fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) {
333 if let Some(def_id) = def_id.as_local() {
334 self.min = VL::new_min(self, def_id);
335 }
336 }
337}
338
339trait VisibilityLike: Sized {
340 const MAX: Self;
341 fn new_min<const SHALLOW: bool>(
342 find: &FindMin<'_, '_, Self, SHALLOW>,
343 def_id: LocalDefId,
344 ) -> Self;
345
346 fn of_impl<const SHALLOW: bool>(
349 def_id: LocalDefId,
350 tcx: TyCtxt<'_>,
351 effective_visibilities: &EffectiveVisibilities,
352 ) -> Self {
353 let mut find = FindMin::<_, SHALLOW> { tcx, effective_visibilities, min: Self::MAX };
354 find.visit(tcx.type_of(def_id).instantiate_identity());
355 if let Some(trait_ref) = tcx.impl_trait_ref(def_id) {
356 find.visit_trait(trait_ref.instantiate_identity());
357 }
358 find.min
359 }
360}
361
362impl VisibilityLike for ty::Visibility {
363 const MAX: Self = ty::Visibility::Public;
364 fn new_min<const SHALLOW: bool>(
365 find: &FindMin<'_, '_, Self, SHALLOW>,
366 def_id: LocalDefId,
367 ) -> Self {
368 min(find.tcx.local_visibility(def_id), find.min, find.tcx)
369 }
370}
371
372impl VisibilityLike for EffectiveVisibility {
373 const MAX: Self = EffectiveVisibility::from_vis(ty::Visibility::Public);
374 fn new_min<const SHALLOW: bool>(
375 find: &FindMin<'_, '_, Self, SHALLOW>,
376 def_id: LocalDefId,
377 ) -> Self {
378 let effective_vis =
379 find.effective_visibilities.effective_vis(def_id).copied().unwrap_or_else(|| {
380 let private_vis = ty::Visibility::Restricted(
381 find.tcx.parent_module_from_def_id(def_id).to_local_def_id(),
382 );
383 EffectiveVisibility::from_vis(private_vis)
384 });
385
386 effective_vis.min(find.min, find.tcx)
387 }
388}
389
390struct EmbargoVisitor<'tcx> {
395 tcx: TyCtxt<'tcx>,
396
397 effective_visibilities: EffectiveVisibilities,
399 macro_reachable: FxHashSet<(LocalModDefId, LocalModDefId)>,
412 changed: bool,
414}
415
416struct ReachEverythingInTheInterfaceVisitor<'a, 'tcx> {
417 effective_vis: EffectiveVisibility,
418 item_def_id: LocalDefId,
419 ev: &'a mut EmbargoVisitor<'tcx>,
420 level: Level,
421}
422
423impl<'tcx> EmbargoVisitor<'tcx> {
424 fn get(&self, def_id: LocalDefId) -> Option<EffectiveVisibility> {
425 self.effective_visibilities.effective_vis(def_id).copied()
426 }
427
428 fn update(
430 &mut self,
431 def_id: LocalDefId,
432 inherited_effective_vis: EffectiveVisibility,
433 level: Level,
434 ) {
435 let nominal_vis = self.tcx.local_visibility(def_id);
436 self.update_eff_vis(def_id, inherited_effective_vis, Some(nominal_vis), level);
437 }
438
439 fn update_eff_vis(
440 &mut self,
441 def_id: LocalDefId,
442 inherited_effective_vis: EffectiveVisibility,
443 max_vis: Option<ty::Visibility>,
444 level: Level,
445 ) {
446 let private_vis =
448 ty::Visibility::Restricted(self.tcx.parent_module_from_def_id(def_id).into());
449 if max_vis != Some(private_vis) {
450 self.changed |= self.effective_visibilities.update(
451 def_id,
452 max_vis,
453 || private_vis,
454 inherited_effective_vis,
455 level,
456 self.tcx,
457 );
458 }
459 }
460
461 fn reach(
462 &mut self,
463 def_id: LocalDefId,
464 effective_vis: EffectiveVisibility,
465 ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
466 ReachEverythingInTheInterfaceVisitor {
467 effective_vis,
468 item_def_id: def_id,
469 ev: self,
470 level: Level::Reachable,
471 }
472 }
473
474 fn reach_through_impl_trait(
475 &mut self,
476 def_id: LocalDefId,
477 effective_vis: EffectiveVisibility,
478 ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
479 ReachEverythingInTheInterfaceVisitor {
480 effective_vis,
481 item_def_id: def_id,
482 ev: self,
483 level: Level::ReachableThroughImplTrait,
484 }
485 }
486
487 fn update_reachability_from_macro(
490 &mut self,
491 local_def_id: LocalDefId,
492 md: &MacroDef,
493 macro_ev: EffectiveVisibility,
494 ) {
495 let hir_id = self.tcx.local_def_id_to_hir_id(local_def_id);
497 let attrs = self.tcx.hir_attrs(hir_id);
498
499 if find_attr!(attrs, AttributeKind::MacroTransparency(x) => *x)
500 .unwrap_or(Transparency::fallback(md.macro_rules))
501 != Transparency::Opaque
502 {
503 return;
504 }
505
506 let macro_module_def_id = self.tcx.local_parent(local_def_id);
507 if self.tcx.def_kind(macro_module_def_id) != DefKind::Mod {
508 return;
510 }
511 let macro_module_def_id = LocalModDefId::new_unchecked(macro_module_def_id);
513
514 if self.effective_visibilities.public_at_level(local_def_id).is_none() {
515 return;
516 }
517
518 let mut module_def_id = macro_module_def_id;
521 loop {
522 let changed_reachability =
523 self.update_macro_reachable(module_def_id, macro_module_def_id, macro_ev);
524 if changed_reachability || module_def_id == LocalModDefId::CRATE_DEF_ID {
525 break;
526 }
527 module_def_id = LocalModDefId::new_unchecked(self.tcx.local_parent(module_def_id));
528 }
529 }
530
531 fn update_macro_reachable(
534 &mut self,
535 module_def_id: LocalModDefId,
536 defining_mod: LocalModDefId,
537 macro_ev: EffectiveVisibility,
538 ) -> bool {
539 if self.macro_reachable.insert((module_def_id, defining_mod)) {
540 for child in self.tcx.module_children_local(module_def_id.to_local_def_id()) {
541 if let Res::Def(def_kind, def_id) = child.res
542 && let Some(def_id) = def_id.as_local()
543 && child.vis.is_accessible_from(defining_mod, self.tcx)
544 {
545 let vis = self.tcx.local_visibility(def_id);
546 self.update_macro_reachable_def(def_id, def_kind, vis, defining_mod, macro_ev);
547 }
548 }
549 true
550 } else {
551 false
552 }
553 }
554
555 fn update_macro_reachable_def(
556 &mut self,
557 def_id: LocalDefId,
558 def_kind: DefKind,
559 vis: ty::Visibility,
560 module: LocalModDefId,
561 macro_ev: EffectiveVisibility,
562 ) {
563 self.update(def_id, macro_ev, Level::Reachable);
564 match def_kind {
565 DefKind::Const | DefKind::Static { .. } | DefKind::TraitAlias | DefKind::TyAlias => {
567 if vis.is_accessible_from(module, self.tcx) {
568 self.update(def_id, macro_ev, Level::Reachable);
569 }
570 }
571
572 DefKind::Macro(_) => {
577 let item = self.tcx.hir_expect_item(def_id);
578 if let hir::ItemKind::Macro(_, MacroDef { macro_rules: false, .. }, _) = item.kind {
579 if vis.is_accessible_from(module, self.tcx) {
580 self.update(def_id, macro_ev, Level::Reachable);
581 }
582 }
583 }
584
585 DefKind::Mod => {
590 if vis.is_accessible_from(module, self.tcx) {
591 self.update_macro_reachable(
592 LocalModDefId::new_unchecked(def_id),
593 module,
594 macro_ev,
595 );
596 }
597 }
598
599 DefKind::Struct | DefKind::Union => {
600 let struct_def = self.tcx.adt_def(def_id);
602 for field in &struct_def.non_enum_variant().fields {
603 let def_id = field.did.expect_local();
604 let field_vis = self.tcx.local_visibility(def_id);
605 if field_vis.is_accessible_from(module, self.tcx) {
606 self.reach(def_id, macro_ev).ty();
607 }
608 }
609 }
610
611 DefKind::AssocConst
614 | DefKind::AssocTy
615 | DefKind::ConstParam
616 | DefKind::Ctor(_, _)
617 | DefKind::Enum
618 | DefKind::ForeignTy
619 | DefKind::Fn
620 | DefKind::OpaqueTy
621 | DefKind::AssocFn
622 | DefKind::Trait
623 | DefKind::TyParam
624 | DefKind::Variant
625 | DefKind::LifetimeParam
626 | DefKind::ExternCrate
627 | DefKind::Use
628 | DefKind::ForeignMod
629 | DefKind::AnonConst
630 | DefKind::InlineConst
631 | DefKind::Field
632 | DefKind::GlobalAsm
633 | DefKind::Impl { .. }
634 | DefKind::Closure
635 | DefKind::SyntheticCoroutineBody => (),
636 }
637 }
638}
639
640impl<'tcx> EmbargoVisitor<'tcx> {
641 fn check_def_id(&mut self, owner_id: OwnerId) {
642 let item_ev = self.get(owner_id.def_id);
645 match self.tcx.def_kind(owner_id) {
646 DefKind::Use | DefKind::ExternCrate | DefKind::GlobalAsm => {}
648 DefKind::Mod => {}
650 DefKind::Macro { .. } => {
651 if let Some(item_ev) = item_ev {
652 let (_, macro_def, _) =
653 self.tcx.hir_expect_item(owner_id.def_id).expect_macro();
654 self.update_reachability_from_macro(owner_id.def_id, macro_def, item_ev);
655 }
656 }
657 DefKind::ForeignTy
658 | DefKind::Const
659 | DefKind::Static { .. }
660 | DefKind::Fn
661 | DefKind::TyAlias => {
662 if let Some(item_ev) = item_ev {
663 self.reach(owner_id.def_id, item_ev).generics().predicates().ty();
664 }
665 }
666 DefKind::Trait => {
667 if let Some(item_ev) = item_ev {
668 self.reach(owner_id.def_id, item_ev).generics().predicates();
669
670 for assoc_item in self.tcx.associated_items(owner_id).in_definition_order() {
671 if assoc_item.is_impl_trait_in_trait() {
672 continue;
673 }
674
675 let def_id = assoc_item.def_id.expect_local();
676 self.update(def_id, item_ev, Level::Reachable);
677
678 let tcx = self.tcx;
679 let mut reach = self.reach(def_id, item_ev);
680 reach.generics().predicates();
681
682 if assoc_item.is_type() && !assoc_item.defaultness(tcx).has_value() {
683 } else {
685 reach.ty();
686 }
687 }
688 }
689 }
690 DefKind::TraitAlias => {
691 if let Some(item_ev) = item_ev {
692 self.reach(owner_id.def_id, item_ev).generics().predicates();
693 }
694 }
695 DefKind::Impl { of_trait } => {
696 let item_ev = EffectiveVisibility::of_impl::<true>(
707 owner_id.def_id,
708 self.tcx,
709 &self.effective_visibilities,
710 );
711
712 self.update_eff_vis(owner_id.def_id, item_ev, None, Level::Direct);
713
714 self.reach(owner_id.def_id, item_ev).generics().predicates().ty().trait_ref();
715
716 for assoc_item in self.tcx.associated_items(owner_id).in_definition_order() {
717 if assoc_item.is_impl_trait_in_trait() {
718 continue;
719 }
720
721 let def_id = assoc_item.def_id.expect_local();
722 let max_vis =
723 if of_trait { None } else { Some(self.tcx.local_visibility(def_id)) };
724 self.update_eff_vis(def_id, item_ev, max_vis, Level::Direct);
725
726 if let Some(impl_item_ev) = self.get(def_id) {
727 self.reach(def_id, impl_item_ev).generics().predicates().ty();
728 }
729 }
730 }
731 DefKind::Enum => {
732 if let Some(item_ev) = item_ev {
733 self.reach(owner_id.def_id, item_ev).generics().predicates();
734 }
735 let def = self.tcx.adt_def(owner_id);
736 for variant in def.variants() {
737 if let Some(item_ev) = item_ev {
738 self.update(variant.def_id.expect_local(), item_ev, Level::Reachable);
739 }
740
741 if let Some(variant_ev) = self.get(variant.def_id.expect_local()) {
742 if let Some(ctor_def_id) = variant.ctor_def_id() {
743 self.update(ctor_def_id.expect_local(), variant_ev, Level::Reachable);
744 }
745
746 for field in &variant.fields {
747 let field = field.did.expect_local();
748 self.update(field, variant_ev, Level::Reachable);
749 self.reach(field, variant_ev).ty();
750 }
751 self.reach(owner_id.def_id, variant_ev).ty();
754 }
755 if let Some(ctor_def_id) = variant.ctor_def_id() {
756 if let Some(ctor_ev) = self.get(ctor_def_id.expect_local()) {
757 self.reach(owner_id.def_id, ctor_ev).ty();
758 }
759 }
760 }
761 }
762 DefKind::Struct | DefKind::Union => {
763 let def = self.tcx.adt_def(owner_id).non_enum_variant();
764 if let Some(item_ev) = item_ev {
765 self.reach(owner_id.def_id, item_ev).generics().predicates();
766 for field in &def.fields {
767 let field = field.did.expect_local();
768 self.update(field, item_ev, Level::Reachable);
769 if let Some(field_ev) = self.get(field) {
770 self.reach(field, field_ev).ty();
771 }
772 }
773 }
774 if let Some(ctor_def_id) = def.ctor_def_id() {
775 if let Some(item_ev) = item_ev {
776 self.update(ctor_def_id.expect_local(), item_ev, Level::Reachable);
777 }
778 if let Some(ctor_ev) = self.get(ctor_def_id.expect_local()) {
779 self.reach(owner_id.def_id, ctor_ev).ty();
780 }
781 }
782 }
783 DefKind::ForeignMod => {}
785 DefKind::Field
786 | DefKind::Variant
787 | DefKind::AssocFn
788 | DefKind::AssocTy
789 | DefKind::AssocConst
790 | DefKind::TyParam
791 | DefKind::AnonConst
792 | DefKind::InlineConst
793 | DefKind::OpaqueTy
794 | DefKind::Closure
795 | DefKind::SyntheticCoroutineBody
796 | DefKind::ConstParam
797 | DefKind::LifetimeParam
798 | DefKind::Ctor(..) => {
799 bug!("should be checked while checking parent")
800 }
801 }
802 }
803}
804
805impl ReachEverythingInTheInterfaceVisitor<'_, '_> {
806 fn generics(&mut self) -> &mut Self {
807 for param in &self.ev.tcx.generics_of(self.item_def_id).own_params {
808 if let GenericParamDefKind::Const { .. } = param.kind {
809 self.visit(self.ev.tcx.type_of(param.def_id).instantiate_identity());
810 }
811 if let Some(default) = param.default_value(self.ev.tcx) {
812 self.visit(default.instantiate_identity());
813 }
814 }
815 self
816 }
817
818 fn predicates(&mut self) -> &mut Self {
819 self.visit_predicates(self.ev.tcx.predicates_of(self.item_def_id));
820 self
821 }
822
823 fn ty(&mut self) -> &mut Self {
824 self.visit(self.ev.tcx.type_of(self.item_def_id).instantiate_identity());
825 self
826 }
827
828 fn trait_ref(&mut self) -> &mut Self {
829 if let Some(trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) {
830 self.visit_trait(trait_ref.instantiate_identity());
831 }
832 self
833 }
834}
835
836impl<'tcx> DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
837 fn tcx(&self) -> TyCtxt<'tcx> {
838 self.ev.tcx
839 }
840 fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) {
841 if let Some(def_id) = def_id.as_local() {
842 let max_vis = (self.level != Level::ReachableThroughImplTrait)
846 .then(|| self.ev.tcx.local_visibility(def_id));
847 self.ev.update_eff_vis(def_id, self.effective_vis, max_vis, self.level);
848 }
849 }
850}
851
852pub struct TestReachabilityVisitor<'a, 'tcx> {
856 tcx: TyCtxt<'tcx>,
857 effective_visibilities: &'a EffectiveVisibilities,
858}
859
860impl<'a, 'tcx> TestReachabilityVisitor<'a, 'tcx> {
861 fn effective_visibility_diagnostic(&self, def_id: LocalDefId) {
862 if self.tcx.has_attr(def_id, sym::rustc_effective_visibility) {
863 let mut error_msg = String::new();
864 let span = self.tcx.def_span(def_id.to_def_id());
865 if let Some(effective_vis) = self.effective_visibilities.effective_vis(def_id) {
866 for level in Level::all_levels() {
867 let vis_str = effective_vis.at_level(level).to_string(def_id, self.tcx);
868 if level != Level::Direct {
869 error_msg.push_str(", ");
870 }
871 error_msg.push_str(&format!("{level:?}: {vis_str}"));
872 }
873 } else {
874 error_msg.push_str("not in the table");
875 }
876 self.tcx.dcx().emit_err(ReportEffectiveVisibility { span, descr: error_msg });
877 }
878 }
879}
880
881impl<'a, 'tcx> TestReachabilityVisitor<'a, 'tcx> {
882 fn check_def_id(&self, owner_id: OwnerId) {
883 self.effective_visibility_diagnostic(owner_id.def_id);
884
885 match self.tcx.def_kind(owner_id) {
886 DefKind::Enum => {
887 let def = self.tcx.adt_def(owner_id.def_id);
888 for variant in def.variants() {
889 self.effective_visibility_diagnostic(variant.def_id.expect_local());
890 if let Some(ctor_def_id) = variant.ctor_def_id() {
891 self.effective_visibility_diagnostic(ctor_def_id.expect_local());
892 }
893 for field in &variant.fields {
894 self.effective_visibility_diagnostic(field.did.expect_local());
895 }
896 }
897 }
898 DefKind::Struct | DefKind::Union => {
899 let def = self.tcx.adt_def(owner_id.def_id).non_enum_variant();
900 if let Some(ctor_def_id) = def.ctor_def_id() {
901 self.effective_visibility_diagnostic(ctor_def_id.expect_local());
902 }
903 for field in &def.fields {
904 self.effective_visibility_diagnostic(field.did.expect_local());
905 }
906 }
907 _ => {}
908 }
909 }
910}
911
912struct NamePrivacyVisitor<'tcx> {
920 tcx: TyCtxt<'tcx>,
921 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
922}
923
924impl<'tcx> NamePrivacyVisitor<'tcx> {
925 #[track_caller]
929 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
930 self.maybe_typeck_results
931 .expect("`NamePrivacyVisitor::typeck_results` called outside of body")
932 }
933
934 fn check_field(
936 &mut self,
937 hir_id: hir::HirId, use_ctxt: Span, def: ty::AdtDef<'tcx>, field: &'tcx ty::FieldDef,
941 ) -> bool {
942 if def.is_enum() {
943 return true;
944 }
945
946 let ident = Ident::new(sym::dummy, use_ctxt);
948 let (_, def_id) = self.tcx.adjust_ident_and_get_scope(ident, def.did(), hir_id);
949 !field.vis.is_accessible_from(def_id, self.tcx)
950 }
951
952 fn emit_unreachable_field_error(
954 &mut self,
955 fields: Vec<(Symbol, Span, bool )>,
956 def: ty::AdtDef<'tcx>, update_syntax: Option<Span>,
958 struct_span: Span,
959 ) {
960 if def.is_enum() || fields.is_empty() {
961 return;
962 }
963
964 let Some(field_names) = listify(&fields[..], |(n, _, _)| format!("`{n}`")) else { return };
976 let span: MultiSpan = fields.iter().map(|(_, span, _)| *span).collect::<Vec<Span>>().into();
977
978 let rest_field_names: Vec<_> =
980 fields.iter().filter(|(_, _, is_present)| !is_present).map(|(n, _, _)| n).collect();
981 let rest_len = rest_field_names.len();
982 let rest_field_names =
983 listify(&rest_field_names[..], |n| format!("`{n}`")).unwrap_or_default();
984 let labels = fields
986 .iter()
987 .filter(|(_, _, is_present)| *is_present)
988 .map(|(_, span, _)| FieldIsPrivateLabel::Other { span: *span })
989 .chain(update_syntax.iter().map(|span| FieldIsPrivateLabel::IsUpdateSyntax {
990 span: *span,
991 rest_field_names: rest_field_names.clone(),
992 rest_len,
993 }))
994 .collect();
995
996 self.tcx.dcx().emit_err(FieldIsPrivate {
997 span,
998 struct_span: if self
999 .tcx
1000 .sess
1001 .source_map()
1002 .is_multiline(fields[0].1.between(struct_span))
1003 {
1004 Some(struct_span)
1005 } else {
1006 None
1007 },
1008 field_names,
1009 variant_descr: def.variant_descr(),
1010 def_path_str: self.tcx.def_path_str(def.did()),
1011 labels,
1012 len: fields.len(),
1013 });
1014 }
1015
1016 fn check_expanded_fields(
1017 &mut self,
1018 adt: ty::AdtDef<'tcx>,
1019 variant: &'tcx ty::VariantDef,
1020 fields: &[hir::ExprField<'tcx>],
1021 hir_id: hir::HirId,
1022 span: Span,
1023 struct_span: Span,
1024 ) {
1025 let mut failed_fields = vec![];
1026 for (vf_index, variant_field) in variant.fields.iter_enumerated() {
1027 let field =
1028 fields.iter().find(|f| self.typeck_results().field_index(f.hir_id) == vf_index);
1029 let (hir_id, use_ctxt, span) = match field {
1030 Some(field) => (field.hir_id, field.ident.span, field.span),
1031 None => (hir_id, span, span),
1032 };
1033 if self.check_field(hir_id, use_ctxt, adt, variant_field) {
1034 let name = match field {
1035 Some(field) => field.ident.name,
1036 None => variant_field.name,
1037 };
1038 failed_fields.push((name, span, field.is_some()));
1039 }
1040 }
1041 self.emit_unreachable_field_error(failed_fields, adt, Some(span), struct_span);
1042 }
1043}
1044
1045impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> {
1046 fn visit_nested_body(&mut self, body_id: hir::BodyId) {
1047 let new_typeck_results = self.tcx.typeck_body(body_id);
1048 if new_typeck_results.tainted_by_errors.is_some() {
1050 return;
1051 }
1052 let old_maybe_typeck_results = self.maybe_typeck_results.replace(new_typeck_results);
1053 self.visit_body(self.tcx.hir_body(body_id));
1054 self.maybe_typeck_results = old_maybe_typeck_results;
1055 }
1056
1057 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1058 if let hir::ExprKind::Struct(qpath, fields, ref base) = expr.kind {
1059 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
1060 let adt = self.typeck_results().expr_ty(expr).ty_adt_def().unwrap();
1061 let variant = adt.variant_of_res(res);
1062 match *base {
1063 hir::StructTailExpr::Base(base) => {
1064 self.check_expanded_fields(
1068 adt,
1069 variant,
1070 fields,
1071 base.hir_id,
1072 base.span,
1073 qpath.span(),
1074 );
1075 }
1076 hir::StructTailExpr::DefaultFields(span) => {
1077 self.check_expanded_fields(
1078 adt,
1079 variant,
1080 fields,
1081 expr.hir_id,
1082 span,
1083 qpath.span(),
1084 );
1085 }
1086 hir::StructTailExpr::None => {
1087 let mut failed_fields = vec![];
1088 for field in fields {
1089 let (hir_id, use_ctxt) = (field.hir_id, field.ident.span);
1090 let index = self.typeck_results().field_index(field.hir_id);
1091 if self.check_field(hir_id, use_ctxt, adt, &variant.fields[index]) {
1092 failed_fields.push((field.ident.name, field.ident.span, true));
1093 }
1094 }
1095 self.emit_unreachable_field_error(failed_fields, adt, None, qpath.span());
1096 }
1097 }
1098 }
1099
1100 intravisit::walk_expr(self, expr);
1101 }
1102
1103 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
1104 if let PatKind::Struct(ref qpath, fields, _) = pat.kind {
1105 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
1106 let adt = self.typeck_results().pat_ty(pat).ty_adt_def().unwrap();
1107 let variant = adt.variant_of_res(res);
1108 let mut failed_fields = vec![];
1109 for field in fields {
1110 let (hir_id, use_ctxt) = (field.hir_id, field.ident.span);
1111 let index = self.typeck_results().field_index(field.hir_id);
1112 if self.check_field(hir_id, use_ctxt, adt, &variant.fields[index]) {
1113 failed_fields.push((field.ident.name, field.ident.span, true));
1114 }
1115 }
1116 self.emit_unreachable_field_error(failed_fields, adt, None, qpath.span());
1117 }
1118
1119 intravisit::walk_pat(self, pat);
1120 }
1121}
1122
1123struct TypePrivacyVisitor<'tcx> {
1130 tcx: TyCtxt<'tcx>,
1131 module_def_id: LocalModDefId,
1132 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
1133 span: Span,
1134}
1135
1136impl<'tcx> TypePrivacyVisitor<'tcx> {
1137 fn item_is_accessible(&self, did: DefId) -> bool {
1138 self.tcx.visibility(did).is_accessible_from(self.module_def_id, self.tcx)
1139 }
1140
1141 fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
1143 self.span = span;
1144 let typeck_results = self
1145 .maybe_typeck_results
1146 .unwrap_or_else(|| span_bug!(span, "`hir::Expr` or `hir::Pat` outside of a body"));
1147 let result: ControlFlow<()> = try {
1148 self.visit(typeck_results.node_type(id))?;
1149 self.visit(typeck_results.node_args(id))?;
1150 if let Some(adjustments) = typeck_results.adjustments().get(id) {
1151 adjustments.iter().try_for_each(|adjustment| self.visit(adjustment.target))?;
1152 }
1153 };
1154 result.is_break()
1155 }
1156
1157 fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1158 let is_error = !self.item_is_accessible(def_id);
1159 if is_error {
1160 self.tcx.dcx().emit_err(ItemIsPrivate { span: self.span, kind, descr: descr.into() });
1161 }
1162 is_error
1163 }
1164}
1165
1166impl<'tcx> rustc_ty_utils::sig_types::SpannedTypeVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1167 type Result = ControlFlow<()>;
1168 fn visit(&mut self, span: Span, value: impl TypeVisitable<TyCtxt<'tcx>>) -> Self::Result {
1169 self.span = span;
1170 value.visit_with(&mut self.skeleton())
1171 }
1172}
1173
1174impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> {
1175 fn visit_nested_body(&mut self, body_id: hir::BodyId) {
1176 let old_maybe_typeck_results =
1177 self.maybe_typeck_results.replace(self.tcx.typeck_body(body_id));
1178 self.visit_body(self.tcx.hir_body(body_id));
1179 self.maybe_typeck_results = old_maybe_typeck_results;
1180 }
1181
1182 fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx, AmbigArg>) {
1183 self.span = hir_ty.span;
1184 if self
1185 .visit(
1186 self.maybe_typeck_results
1187 .unwrap_or_else(|| span_bug!(hir_ty.span, "`hir::Ty` outside of a body"))
1188 .node_type(hir_ty.hir_id),
1189 )
1190 .is_break()
1191 {
1192 return;
1193 }
1194
1195 intravisit::walk_ty(self, hir_ty);
1196 }
1197
1198 fn visit_infer(
1199 &mut self,
1200 inf_id: rustc_hir::HirId,
1201 inf_span: Span,
1202 _kind: InferKind<'tcx>,
1203 ) -> Self::Result {
1204 self.span = inf_span;
1205 if let Some(ty) = self
1206 .maybe_typeck_results
1207 .unwrap_or_else(|| span_bug!(inf_span, "Inference variable outside of a body"))
1208 .node_type_opt(inf_id)
1209 {
1210 if self.visit(ty).is_break() {
1211 return;
1212 }
1213 } else {
1214 }
1216
1217 self.visit_id(inf_id)
1218 }
1219
1220 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1222 if self.check_expr_pat_type(expr.hir_id, expr.span) {
1223 return;
1225 }
1226 match expr.kind {
1227 hir::ExprKind::Assign(_, rhs, _) | hir::ExprKind::Match(rhs, ..) => {
1228 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
1230 return;
1231 }
1232 }
1233 hir::ExprKind::MethodCall(segment, ..) => {
1234 self.span = segment.ident.span;
1236 let typeck_results = self
1237 .maybe_typeck_results
1238 .unwrap_or_else(|| span_bug!(self.span, "`hir::Expr` outside of a body"));
1239 if let Some(def_id) = typeck_results.type_dependent_def_id(expr.hir_id) {
1240 if self.visit(self.tcx.type_of(def_id).instantiate_identity()).is_break() {
1241 return;
1242 }
1243 } else {
1244 self.tcx
1245 .dcx()
1246 .span_delayed_bug(expr.span, "no type-dependent def for method call");
1247 }
1248 }
1249 _ => {}
1250 }
1251
1252 intravisit::walk_expr(self, expr);
1253 }
1254
1255 fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) {
1262 let def = match qpath {
1263 hir::QPath::Resolved(_, path) => match path.res {
1264 Res::Def(kind, def_id) => Some((kind, def_id)),
1265 _ => None,
1266 },
1267 hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => {
1268 match self.maybe_typeck_results {
1269 Some(typeck_results) => typeck_results.type_dependent_def(id),
1270 None => None,
1272 }
1273 }
1274 };
1275 let def = def.filter(|(kind, _)| {
1276 matches!(
1277 kind,
1278 DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static { .. }
1279 )
1280 });
1281 if let Some((kind, def_id)) = def {
1282 let is_local_static =
1283 if let DefKind::Static { .. } = kind { def_id.is_local() } else { false };
1284 if !self.item_is_accessible(def_id) && !is_local_static {
1285 let name = match *qpath {
1286 hir::QPath::LangItem(it, ..) => {
1287 self.tcx.lang_items().get(it).map(|did| self.tcx.def_path_str(did))
1288 }
1289 hir::QPath::Resolved(_, path) => Some(self.tcx.def_path_str(path.res.def_id())),
1290 hir::QPath::TypeRelative(_, segment) => Some(segment.ident.to_string()),
1291 };
1292 let kind = self.tcx.def_descr(def_id);
1293 let sess = self.tcx.sess;
1294 let _ = match name {
1295 Some(name) => {
1296 sess.dcx().emit_err(ItemIsPrivate { span, kind, descr: (&name).into() })
1297 }
1298 None => sess.dcx().emit_err(UnnamedItemIsPrivate { span, kind }),
1299 };
1300 return;
1301 }
1302 }
1303
1304 intravisit::walk_qpath(self, qpath, id);
1305 }
1306
1307 fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) {
1309 if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
1310 return;
1312 }
1313
1314 intravisit::walk_pat(self, pattern);
1315 }
1316
1317 fn visit_local(&mut self, local: &'tcx hir::LetStmt<'tcx>) {
1318 if let Some(init) = local.init {
1319 if self.check_expr_pat_type(init.hir_id, init.span) {
1320 return;
1322 }
1323 }
1324
1325 intravisit::walk_local(self, local);
1326 }
1327}
1328
1329impl<'tcx> DefIdVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1330 type Result = ControlFlow<()>;
1331 fn tcx(&self) -> TyCtxt<'tcx> {
1332 self.tcx
1333 }
1334 fn visit_def_id(
1335 &mut self,
1336 def_id: DefId,
1337 kind: &str,
1338 descr: &dyn fmt::Display,
1339 ) -> Self::Result {
1340 if self.check_def_id(def_id, kind, descr) {
1341 ControlFlow::Break(())
1342 } else {
1343 ControlFlow::Continue(())
1344 }
1345 }
1346}
1347
1348struct SearchInterfaceForPrivateItemsVisitor<'tcx> {
1356 tcx: TyCtxt<'tcx>,
1357 item_def_id: LocalDefId,
1358 required_visibility: ty::Visibility,
1360 required_effective_vis: Option<EffectiveVisibility>,
1361 in_assoc_ty: bool,
1362 in_primary_interface: bool,
1363 skip_assoc_tys: bool,
1364}
1365
1366impl SearchInterfaceForPrivateItemsVisitor<'_> {
1367 fn generics(&mut self) -> &mut Self {
1368 self.in_primary_interface = true;
1369 for param in &self.tcx.generics_of(self.item_def_id).own_params {
1370 match param.kind {
1371 GenericParamDefKind::Lifetime => {}
1372 GenericParamDefKind::Type { has_default, .. } => {
1373 if has_default {
1374 let _ = self.visit(self.tcx.type_of(param.def_id).instantiate_identity());
1375 }
1376 }
1377 GenericParamDefKind::Const { .. } => {
1379 let _ = self.visit(self.tcx.type_of(param.def_id).instantiate_identity());
1380 }
1381 }
1382 }
1383 self
1384 }
1385
1386 fn predicates(&mut self) -> &mut Self {
1387 self.in_primary_interface = false;
1388 let _ = self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id));
1395 self
1396 }
1397
1398 fn bounds(&mut self) -> &mut Self {
1399 self.in_primary_interface = false;
1400 let _ = self.visit_clauses(self.tcx.explicit_item_bounds(self.item_def_id).skip_binder());
1401 self
1402 }
1403
1404 fn ty(&mut self) -> &mut Self {
1405 self.in_primary_interface = true;
1406 let _ = self.visit(self.tcx.type_of(self.item_def_id).instantiate_identity());
1407 self
1408 }
1409
1410 fn trait_ref(&mut self) -> &mut Self {
1411 self.in_primary_interface = true;
1412 if let Some(trait_ref) = self.tcx.impl_trait_ref(self.item_def_id) {
1413 let _ = self.visit_trait(trait_ref.instantiate_identity());
1414 }
1415 self
1416 }
1417
1418 fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1419 if self.leaks_private_dep(def_id) {
1420 self.tcx.emit_node_span_lint(
1421 lint::builtin::EXPORTED_PRIVATE_DEPENDENCIES,
1422 self.tcx.local_def_id_to_hir_id(self.item_def_id),
1423 self.tcx.def_span(self.item_def_id.to_def_id()),
1424 FromPrivateDependencyInPublicInterface {
1425 kind,
1426 descr: descr.into(),
1427 krate: self.tcx.crate_name(def_id.krate),
1428 },
1429 );
1430 }
1431
1432 let Some(local_def_id) = def_id.as_local() else {
1433 return false;
1434 };
1435
1436 let vis = self.tcx.local_visibility(local_def_id);
1437 if self.in_assoc_ty && !vis.is_at_least(self.required_visibility, self.tcx) {
1438 let vis_descr = match vis {
1439 ty::Visibility::Public => "public",
1440 ty::Visibility::Restricted(vis_def_id) => {
1441 if vis_def_id
1442 == self.tcx.parent_module_from_def_id(local_def_id).to_local_def_id()
1443 {
1444 "private"
1445 } else if vis_def_id.is_top_level_module() {
1446 "crate-private"
1447 } else {
1448 "restricted"
1449 }
1450 }
1451 };
1452
1453 let span = self.tcx.def_span(self.item_def_id.to_def_id());
1454 let vis_span = self.tcx.def_span(def_id);
1455 self.tcx.dcx().emit_err(InPublicInterface {
1456 span,
1457 vis_descr,
1458 kind,
1459 descr: descr.into(),
1460 vis_span,
1461 });
1462 return false;
1463 }
1464
1465 let Some(effective_vis) = self.required_effective_vis else {
1466 return false;
1467 };
1468
1469 let reachable_at_vis = *effective_vis.at_level(Level::Reachable);
1470
1471 if !vis.is_at_least(reachable_at_vis, self.tcx) {
1472 let lint = if self.in_primary_interface {
1473 lint::builtin::PRIVATE_INTERFACES
1474 } else {
1475 lint::builtin::PRIVATE_BOUNDS
1476 };
1477 let span = self.tcx.def_span(self.item_def_id.to_def_id());
1478 let vis_span = self.tcx.def_span(def_id);
1479 self.tcx.emit_node_span_lint(
1480 lint,
1481 self.tcx.local_def_id_to_hir_id(self.item_def_id),
1482 span,
1483 PrivateInterfacesOrBoundsLint {
1484 item_span: span,
1485 item_kind: self.tcx.def_descr(self.item_def_id.to_def_id()),
1486 item_descr: (&LazyDefPathStr {
1487 def_id: self.item_def_id.to_def_id(),
1488 tcx: self.tcx,
1489 })
1490 .into(),
1491 item_vis_descr: &reachable_at_vis.to_string(self.item_def_id, self.tcx),
1492 ty_span: vis_span,
1493 ty_kind: kind,
1494 ty_descr: descr.into(),
1495 ty_vis_descr: &vis.to_string(local_def_id, self.tcx),
1496 },
1497 );
1498 }
1499
1500 false
1501 }
1502
1503 fn leaks_private_dep(&self, item_id: DefId) -> bool {
1508 let ret = self.required_visibility.is_public() && self.tcx.is_private_dep(item_id.krate);
1509
1510 debug!("leaks_private_dep(item_id={:?})={}", item_id, ret);
1511 ret
1512 }
1513}
1514
1515impl<'tcx> DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> {
1516 type Result = ControlFlow<()>;
1517 fn skip_assoc_tys(&self) -> bool {
1518 self.skip_assoc_tys
1519 }
1520 fn tcx(&self) -> TyCtxt<'tcx> {
1521 self.tcx
1522 }
1523 fn visit_def_id(
1524 &mut self,
1525 def_id: DefId,
1526 kind: &str,
1527 descr: &dyn fmt::Display,
1528 ) -> Self::Result {
1529 if self.check_def_id(def_id, kind, descr) {
1530 ControlFlow::Break(())
1531 } else {
1532 ControlFlow::Continue(())
1533 }
1534 }
1535}
1536
1537struct PrivateItemsInPublicInterfacesChecker<'a, 'tcx> {
1538 tcx: TyCtxt<'tcx>,
1539 effective_visibilities: &'a EffectiveVisibilities,
1540}
1541
1542impl<'tcx> PrivateItemsInPublicInterfacesChecker<'_, 'tcx> {
1543 fn check(
1544 &self,
1545 def_id: LocalDefId,
1546 required_visibility: ty::Visibility,
1547 required_effective_vis: Option<EffectiveVisibility>,
1548 ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> {
1549 SearchInterfaceForPrivateItemsVisitor {
1550 tcx: self.tcx,
1551 item_def_id: def_id,
1552 required_visibility,
1553 required_effective_vis,
1554 in_assoc_ty: false,
1555 in_primary_interface: true,
1556 skip_assoc_tys: false,
1557 }
1558 }
1559
1560 fn check_unnameable(&self, def_id: LocalDefId, effective_vis: Option<EffectiveVisibility>) {
1561 let Some(effective_vis) = effective_vis else {
1562 return;
1563 };
1564
1565 let reexported_at_vis = effective_vis.at_level(Level::Reexported);
1566 let reachable_at_vis = effective_vis.at_level(Level::Reachable);
1567
1568 if reachable_at_vis.is_public() && reexported_at_vis != reachable_at_vis {
1569 let hir_id = self.tcx.local_def_id_to_hir_id(def_id);
1570 let span = self.tcx.def_span(def_id.to_def_id());
1571 self.tcx.emit_node_span_lint(
1572 lint::builtin::UNNAMEABLE_TYPES,
1573 hir_id,
1574 span,
1575 UnnameableTypesLint {
1576 span,
1577 kind: self.tcx.def_descr(def_id.to_def_id()),
1578 descr: (&LazyDefPathStr { def_id: def_id.to_def_id(), tcx: self.tcx }).into(),
1579 reachable_vis: &reachable_at_vis.to_string(def_id, self.tcx),
1580 reexported_vis: &reexported_at_vis.to_string(def_id, self.tcx),
1581 },
1582 );
1583 }
1584 }
1585
1586 fn check_assoc_item(
1587 &self,
1588 item: &ty::AssocItem,
1589 vis: ty::Visibility,
1590 effective_vis: Option<EffectiveVisibility>,
1591 ) {
1592 let mut check = self.check(item.def_id.expect_local(), vis, effective_vis);
1593
1594 let (check_ty, is_assoc_ty) = match item.kind {
1595 ty::AssocKind::Const { .. } | ty::AssocKind::Fn { .. } => (true, false),
1596 ty::AssocKind::Type { .. } => (item.defaultness(self.tcx).has_value(), true),
1597 };
1598
1599 check.in_assoc_ty = is_assoc_ty;
1600 check.generics().predicates();
1601 if check_ty {
1602 check.ty();
1603 }
1604 }
1605
1606 fn get(&self, def_id: LocalDefId) -> Option<EffectiveVisibility> {
1607 self.effective_visibilities.effective_vis(def_id).copied()
1608 }
1609
1610 fn check_item(&self, id: ItemId) {
1611 let tcx = self.tcx;
1612 let def_id = id.owner_id.def_id;
1613 let item_visibility = tcx.local_visibility(def_id);
1614 let effective_vis = self.get(def_id);
1615 let def_kind = tcx.def_kind(def_id);
1616
1617 match def_kind {
1618 DefKind::Const | DefKind::Static { .. } | DefKind::Fn | DefKind::TyAlias => {
1619 if let DefKind::TyAlias = def_kind {
1620 self.check_unnameable(def_id, effective_vis);
1621 }
1622 self.check(def_id, item_visibility, effective_vis).generics().predicates().ty();
1623 }
1624 DefKind::OpaqueTy => {
1625 self.check(def_id, item_visibility, effective_vis).generics().bounds();
1628 }
1629 DefKind::Trait => {
1630 self.check_unnameable(def_id, effective_vis);
1631
1632 self.check(def_id, item_visibility, effective_vis).generics().predicates();
1633
1634 for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() {
1635 if assoc_item.is_impl_trait_in_trait() {
1636 continue;
1637 }
1638
1639 self.check_assoc_item(assoc_item, item_visibility, effective_vis);
1640
1641 if assoc_item.is_type() {
1642 self.check(
1643 assoc_item.def_id.expect_local(),
1644 item_visibility,
1645 effective_vis,
1646 )
1647 .bounds();
1648 }
1649 }
1650 }
1651 DefKind::TraitAlias => {
1652 self.check(def_id, item_visibility, effective_vis).generics().predicates();
1653 }
1654 DefKind::Enum => {
1655 self.check_unnameable(def_id, effective_vis);
1656 self.check(def_id, item_visibility, effective_vis).generics().predicates();
1657
1658 let adt = tcx.adt_def(id.owner_id);
1659 for field in adt.all_fields() {
1660 self.check(field.did.expect_local(), item_visibility, effective_vis).ty();
1661 }
1662 }
1663 DefKind::Struct | DefKind::Union => {
1665 self.check_unnameable(def_id, effective_vis);
1666 self.check(def_id, item_visibility, effective_vis).generics().predicates();
1667
1668 let adt = tcx.adt_def(id.owner_id);
1669 for field in adt.all_fields() {
1670 let visibility = min(item_visibility, field.vis.expect_local(), tcx);
1671 let field_ev = self.get(field.did.expect_local());
1672
1673 self.check(field.did.expect_local(), visibility, field_ev).ty();
1674 }
1675 }
1676 DefKind::ForeignMod => {}
1678 DefKind::Impl { of_trait } => {
1683 let impl_vis = ty::Visibility::of_impl::<false>(def_id, tcx, &Default::default());
1684
1685 let impl_ev =
1697 EffectiveVisibility::of_impl::<false>(def_id, tcx, self.effective_visibilities);
1698
1699 let mut check = self.check(def_id, impl_vis, Some(impl_ev));
1700
1701 if !of_trait {
1704 check.generics().predicates();
1705 }
1706
1707 check.skip_assoc_tys = true;
1711 check.ty().trait_ref();
1712
1713 for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() {
1714 if assoc_item.is_impl_trait_in_trait() {
1715 continue;
1716 }
1717
1718 let impl_item_vis = if !of_trait {
1719 min(tcx.local_visibility(assoc_item.def_id.expect_local()), impl_vis, tcx)
1720 } else {
1721 impl_vis
1722 };
1723
1724 let impl_item_ev = if !of_trait {
1725 self.get(assoc_item.def_id.expect_local())
1726 .map(|ev| ev.min(impl_ev, self.tcx))
1727 } else {
1728 Some(impl_ev)
1729 };
1730
1731 self.check_assoc_item(assoc_item, impl_item_vis, impl_item_ev);
1732 }
1733 }
1734 _ => {}
1735 }
1736 }
1737
1738 fn check_foreign_item(&self, id: ForeignItemId) {
1739 let tcx = self.tcx;
1740 let def_id = id.owner_id.def_id;
1741 let item_visibility = tcx.local_visibility(def_id);
1742 let effective_vis = self.get(def_id);
1743
1744 if let DefKind::ForeignTy = self.tcx.def_kind(def_id) {
1745 self.check_unnameable(def_id, effective_vis);
1746 }
1747
1748 self.check(def_id, item_visibility, effective_vis).generics().predicates().ty();
1749 }
1750}
1751
1752pub fn provide(providers: &mut Providers) {
1753 *providers = Providers {
1754 effective_visibilities,
1755 check_private_in_public,
1756 check_mod_privacy,
1757 ..*providers
1758 };
1759}
1760
1761fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
1762 let mut visitor = NamePrivacyVisitor { tcx, maybe_typeck_results: None };
1764 tcx.hir_visit_item_likes_in_module(module_def_id, &mut visitor);
1765
1766 let span = tcx.def_span(module_def_id);
1769 let mut visitor = TypePrivacyVisitor { tcx, module_def_id, maybe_typeck_results: None, span };
1770
1771 let module = tcx.hir_module_items(module_def_id);
1772 for def_id in module.definitions() {
1773 let _ = rustc_ty_utils::sig_types::walk_types(tcx, def_id, &mut visitor);
1774
1775 if let Some(body_id) = tcx.hir_maybe_body_owned_by(def_id) {
1776 visitor.visit_nested_body(body_id.id());
1777 }
1778
1779 if let DefKind::Impl { of_trait: true } = tcx.def_kind(def_id) {
1780 let trait_ref = tcx.impl_trait_ref(def_id).unwrap();
1781 let trait_ref = trait_ref.instantiate_identity();
1782 visitor.span =
1783 tcx.hir_expect_item(def_id).expect_impl().of_trait.unwrap().trait_ref.path.span;
1784 let _ =
1785 visitor.visit_def_id(trait_ref.def_id, "trait", &trait_ref.print_only_trait_path());
1786 }
1787 }
1788}
1789
1790fn effective_visibilities(tcx: TyCtxt<'_>, (): ()) -> &EffectiveVisibilities {
1791 let mut visitor = EmbargoVisitor {
1794 tcx,
1795 effective_visibilities: tcx.resolutions(()).effective_visibilities.clone(),
1796 macro_reachable: Default::default(),
1797 changed: false,
1798 };
1799
1800 visitor.effective_visibilities.check_invariants(tcx);
1801
1802 let impl_trait_pass = !tcx.sess.opts.actually_rustdoc;
1806 if impl_trait_pass {
1807 let krate = tcx.hir_crate_items(());
1810 for id in krate.opaques() {
1811 let opaque = tcx.hir_node_by_def_id(id).expect_opaque_ty();
1812 let should_visit = match opaque.origin {
1813 hir::OpaqueTyOrigin::FnReturn {
1814 parent,
1815 in_trait_or_impl: Some(hir::RpitContext::Trait),
1816 }
1817 | hir::OpaqueTyOrigin::AsyncFn {
1818 parent,
1819 in_trait_or_impl: Some(hir::RpitContext::Trait),
1820 } => match tcx.hir_node_by_def_id(parent).expect_trait_item().expect_fn().1 {
1821 hir::TraitFn::Required(_) => false,
1822 hir::TraitFn::Provided(..) => true,
1823 },
1824
1825 hir::OpaqueTyOrigin::FnReturn {
1828 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
1829 ..
1830 }
1831 | hir::OpaqueTyOrigin::AsyncFn {
1832 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
1833 ..
1834 }
1835 | hir::OpaqueTyOrigin::TyAlias { .. } => true,
1836 };
1837 if should_visit {
1838 let pub_ev = EffectiveVisibility::from_vis(ty::Visibility::Public);
1842 visitor
1843 .reach_through_impl_trait(opaque.def_id, pub_ev)
1844 .generics()
1845 .predicates()
1846 .ty();
1847 }
1848 }
1849
1850 visitor.changed = false;
1851 }
1852
1853 let crate_items = tcx.hir_crate_items(());
1854 loop {
1855 for id in crate_items.free_items() {
1856 visitor.check_def_id(id.owner_id);
1857 }
1858 for id in crate_items.foreign_items() {
1859 visitor.check_def_id(id.owner_id);
1860 }
1861 if visitor.changed {
1862 visitor.changed = false;
1863 } else {
1864 break;
1865 }
1866 }
1867 visitor.effective_visibilities.check_invariants(tcx);
1868
1869 let check_visitor =
1870 TestReachabilityVisitor { tcx, effective_visibilities: &visitor.effective_visibilities };
1871 for id in crate_items.owners() {
1872 check_visitor.check_def_id(id);
1873 }
1874
1875 tcx.arena.alloc(visitor.effective_visibilities)
1876}
1877
1878fn check_private_in_public(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
1879 let effective_visibilities = tcx.effective_visibilities(());
1880 let checker = PrivateItemsInPublicInterfacesChecker { tcx, effective_visibilities };
1882
1883 let crate_items = tcx.hir_module_items(module_def_id);
1884 let _ = crate_items.par_items(|id| Ok(checker.check_item(id)));
1885 let _ = crate_items.par_foreign_items(|id| Ok(checker.check_foreign_item(id)));
1886}