1#![feature(associated_type_defaults)]
3#![feature(default_field_values)]
4#![feature(try_blocks)]
5mod diagnostics;
8
9use std::marker::PhantomData;
10use std::ops::ControlFlow;
11use std::{debug_assert_matches, fmt};
12
13use diagnostics::{
14 FieldIsPrivate, FieldIsPrivateLabel, FromPrivateDependencyInPublicInterface, InPublicInterface,
15 ItemIsPrivate, PrivateInterfacesOrBoundsLint, ReportEffectiveVisibility, UnnameableTypesLint,
16 UnnamedItemIsPrivate,
17};
18use rustc_ast::visit::{VisitorResult, try_visit};
19use rustc_attr_ir::find_attr;
20use rustc_data_structures::fx::{FxHashMap, FxHashSet};
21use rustc_data_structures::indexmap::IndexSet;
22use rustc_data_structures::intern::Interned;
23use rustc_errors::{MultiSpan, listify};
24use rustc_hir::def::{CtorOf, DefKind, Res};
25use rustc_hir::def_id::{DefId, LocalDefId, LocalModId};
26use rustc_hir::intravisit::{self, InferKind, Visitor};
27use rustc_hir::{self as hir, AmbigArg, ForeignItemId, ItemId, OwnerId, PatKind};
28use rustc_lint_defs::builtin::{
29 EXPORTED_PRIVATE_DEPENDENCIES, PRIVATE_BOUNDS, PRIVATE_INTERFACES, UNNAMEABLE_TYPES,
30};
31use rustc_middle::middle::privacy::{EffectiveVisibilities, EffectiveVisibility, Level};
32use rustc_middle::query::Providers;
33use rustc_middle::ty::print::PrintTraitRefExt as _;
34use rustc_middle::ty::{
35 self, AssocContainer, Const, GenericParamDefKind, PredicateProxy, TraitRef, Ty, TyCtxt,
36 TypeSuperVisitable, TypeVisitable, TypeVisitor,
37};
38use rustc_span::{Ident, Span, Symbol, bug, kw, span_bug, sym};
39use tracing::debug;
40
41struct LazyDefPathStr<'tcx> {
46 def_id: DefId,
47 tcx: TyCtxt<'tcx>,
48}
49
50impl<'tcx> fmt::Display for LazyDefPathStr<'tcx> {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 f.write_fmt(format_args!("{0}", self.tcx.def_path_str(self.def_id)))write!(f, "{}", self.tcx.def_path_str(self.def_id))
53 }
54}
55
56pub trait DefIdVisitor<'tcx> {
65 type Result: VisitorResult = ();
66 const SHALLOW: bool = false;
67 fn skip_assoc_tys(&self) -> bool {
68 false
69 }
70
71 fn tcx(&self) -> TyCtxt<'tcx>;
72 fn visit_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display)
76 -> Self::Result;
77
78 fn skeleton(&mut self) -> DefIdVisitorSkeleton<'_, 'tcx, Self> {
80 DefIdVisitorSkeleton {
81 def_id_visitor: self,
82 visited_tys: Default::default(),
83 dummy: Default::default(),
84 }
85 }
86 fn visit(&mut self, ty_fragment: impl TypeVisitable<TyCtxt<'tcx>>) -> Self::Result {
87 ty_fragment.visit_with(&mut self.skeleton())
88 }
89 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> Self::Result {
90 self.skeleton().visit_trait(trait_ref)
91 }
92 fn visit_gen_clauses(&mut self, gen_clauses: ty::GenericClauses<'tcx>) -> Self::Result {
93 self.skeleton().visit_clauses(gen_clauses.clauses)
94 }
95 fn visit_clauses(&mut self, clauses: &[(ty::Clause<'tcx>, Span)]) -> Self::Result {
96 self.skeleton().visit_clauses(clauses)
97 }
98}
99
100pub struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> {
101 def_id_visitor: &'v mut V,
102 visited_tys: FxHashSet<Ty<'tcx>>,
103 dummy: PhantomData<TyCtxt<'tcx>>,
104}
105
106impl<'tcx, V> DefIdVisitorSkeleton<'_, 'tcx, V>
107where
108 V: DefIdVisitor<'tcx> + ?Sized,
109{
110 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> V::Result {
111 let TraitRef { def_id, args, .. } = trait_ref;
112 match ::rustc_ast_ir::visit::VisitorResult::branch(self.def_id_visitor.visit_def_id(def_id,
"trait", &trait_ref.print_only_trait_path())) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(self.def_id_visitor.visit_def_id(
113 def_id,
114 "trait",
115 &trait_ref.print_only_trait_path()
116 ));
117 if V::SHALLOW { V::Result::output() } else { args.visit_with(self) }
118 }
119
120 fn visit_projection_term(&mut self, projection: ty::AliasTerm<'tcx>) -> V::Result {
121 let tcx = self.def_id_visitor.tcx();
122 let (trait_ref, assoc_args) = projection.trait_ref_and_own_args(tcx);
123 match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_trait(trait_ref))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(self.visit_trait(trait_ref));
124 if V::SHALLOW {
125 V::Result::output()
126 } else {
127 V::Result::from_branch(
128 assoc_args.iter().try_for_each(|arg| arg.visit_with(self).branch()),
129 )
130 }
131 }
132
133 fn visit_clause(&mut self, clause: ty::Binder<'tcx, ty::ClauseKind<'tcx>>) -> V::Result {
134 match clause.skip_binder() {
135 ty::ClauseKind::Trait(ty::TraitClause { trait_ref, polarity: _ }) => {
136 self.visit_trait(trait_ref)
137 }
138 ty::ClauseKind::HostEffect(clause) => {
139 match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_trait(clause.trait_ref))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(self.visit_trait(clause.trait_ref));
140 clause.constness.visit_with(self)
141 }
142 ty::ClauseKind::Projection(ty::ProjectionClause {
143 projection_term: projection_ty,
144 term,
145 }) => {
146 match ::rustc_ast_ir::visit::VisitorResult::branch(term.visit_with(self)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(term.visit_with(self));
147 self.visit_projection_term(projection_ty)
148 }
149 ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ty, _region)) => ty.visit_with(self),
150 ty::ClauseKind::RegionOutlives(..) => V::Result::output(),
151 ty::ClauseKind::ConstArgHasType(ct, ty) => {
152 match ::rustc_ast_ir::visit::VisitorResult::branch(ct.visit_with(self)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(ct.visit_with(self));
153 ty.visit_with(self)
154 }
155 ty::ClauseKind::ConstEvaluatable(ct) => ct.visit_with(self),
156 ty::ClauseKind::WellFormed(term) => term.visit_with(self),
157 ty::ClauseKind::UnstableFeature(_) => V::Result::output(),
158 ty::ClauseKind::CompressedTrait(_) => ::core::panicking::unreachable_default_msg()unreachable!(),
159 }
160 }
161
162 fn visit_clauses(&mut self, clauses: &[(ty::Clause<'tcx>, Span)]) -> V::Result {
163 for &(clause, _) in clauses {
164 match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_clause(clause.kind()))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(self.visit_clause(clause.kind()));
165 }
166 V::Result::output()
167 }
168}
169
170impl<'tcx, V> TypeVisitor<TyCtxt<'tcx>> for DefIdVisitorSkeleton<'_, 'tcx, V>
171where
172 V: DefIdVisitor<'tcx> + ?Sized,
173{
174 type Result = V::Result;
175
176 fn visit_predicate<P: PredicateProxy<TyCtxt<'tcx>>>(&mut self, p: P) -> Self::Result {
177 self.visit_clause(p.clause_kind_unchecked().unwrap())
178 }
179
180 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
181 let tcx = self.def_id_visitor.tcx();
182 let ty_kind = *ty.kind();
185 match ty_kind {
186 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), ..)
187 | ty::View(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 match ::rustc_ast_ir::visit::VisitorResult::branch(self.def_id_visitor.visit_def_id(def_id,
"type", &ty)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};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 match ::rustc_ast_ir::visit::VisitorResult::branch(tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip().visit_with(self))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(
203 tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip().visit_with(self)
204 );
205 }
206 if let Some(assoc_item) = tcx.opt_associated_item(def_id)
211 && let Some(impl_def_id) = assoc_item.impl_container(tcx)
212 {
213 match ::rustc_ast_ir::visit::VisitorResult::branch(tcx.type_of(impl_def_id).instantiate_identity().skip_norm_wip().visit_with(self))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(
214 tcx.type_of(impl_def_id)
215 .instantiate_identity()
216 .skip_norm_wip()
217 .visit_with(self)
218 );
219 }
220 }
221 ty::Alias(
222 _,
223 data @ ty::AliasTy {
224 kind:
225 kind @ (ty::Inherent { def_id }
226 | ty::Free { def_id }
227 | ty::Projection { def_id }),
228 ..
229 },
230 ) => {
231 if self.def_id_visitor.skip_assoc_tys() {
232 return V::Result::output();
238 }
239 if !self.visited_tys.insert(ty) {
240 return V::Result::output();
244 }
245
246 match ::rustc_ast_ir::visit::VisitorResult::branch(self.def_id_visitor.visit_def_id(def_id,
match kind {
ty::Inherent { .. } | ty::Projection { .. } =>
"associated type",
ty::Free { .. } => "type alias",
ty::Opaque { .. } =>
::core::panicking::unreachable_default_msg(),
}, &LazyDefPathStr { def_id, tcx })) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(self.def_id_visitor.visit_def_id(
247 def_id,
248 match kind {
249 ty::Inherent { .. } | ty::Projection { .. } => "associated type",
250 ty::Free { .. } => "type alias",
251 ty::Opaque { .. } => unreachable!(),
252 },
253 &LazyDefPathStr { def_id, tcx },
254 ));
255
256 return if V::SHALLOW {
258 V::Result::output()
259 } else if #[allow(non_exhaustive_omitted_patterns)] match kind {
ty::Projection { .. } => true,
_ => false,
}matches!(kind, ty::Projection { .. }) {
260 self.visit_projection_term(data.into())
261 } else {
262 V::Result::from_branch(
263 data.args.iter().try_for_each(|arg| arg.visit_with(self).branch()),
264 )
265 };
266 }
267 ty::Dynamic(predicates, ..) => {
268 for predicate in predicates {
271 let trait_ref = match predicate.skip_binder() {
272 ty::ExistentialPredicate::Trait(trait_ref) => trait_ref,
273 ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx),
274 ty::ExistentialPredicate::AutoTrait(def_id) => {
275 ty::ExistentialTraitRef::new(tcx, def_id, ty::GenericArgs::empty())
276 }
277 };
278 let ty::ExistentialTraitRef { def_id, .. } = trait_ref;
279 match ::rustc_ast_ir::visit::VisitorResult::branch(self.def_id_visitor.visit_def_id(def_id,
"trait", &trait_ref)) {
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref));
280 }
281 }
282 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }) => {
283 if self.visited_tys.insert(ty) {
285 match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_clauses(tcx.explicit_item_bounds(def_id).skip_binder()))
{
core::ops::ControlFlow::Continue(()) =>
(),
#[allow(unreachable_code)]
core::ops::ControlFlow::Break(r) => {
return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
}
};try_visit!(self.visit_clauses(tcx.explicit_item_bounds(def_id).skip_binder()));
293 }
294 }
295 ty::Bool
298 | ty::Char
299 | ty::Int(..)
300 | ty::Uint(..)
301 | ty::Float(..)
302 | ty::Str
303 | ty::Never
304 | ty::Array(..)
305 | ty::Slice(..)
306 | ty::Tuple(..)
307 | ty::RawPtr(..)
308 | ty::Ref(..)
309 | ty::Pat(..)
310 | ty::FnPtr(..)
311 | ty::UnsafeBinder(_)
312 | ty::Param(..)
313 | ty::Bound(..)
314 | ty::Error(_)
315 | ty::CoroutineWitness(..) => {}
316 ty::Placeholder(..) | ty::Infer(..) => {
317 ::rustc_span::macros::bug_impl(None,
format_args!("unexpected type: {0:?}", ty), Location::caller())bug!("unexpected type: {:?}", ty)
318 }
319 }
320
321 if V::SHALLOW { V::Result::output() } else { ty.super_visit_with(self) }
322 }
323
324 fn visit_const(&mut self, c: Const<'tcx>) -> Self::Result {
325 let tcx = self.def_id_visitor.tcx();
326 tcx.expand_abstract_consts(c).super_visit_with(self)
327 }
328}
329
330fn assoc_has_type_of(tcx: TyCtxt<'_>, item: &ty::AssocItem) -> bool {
331 if let ty::AssocKind::Type { data: ty::AssocTypeData::Normal(..) } = item.kind
332 && let hir::Node::TraitItem(item) =
333 tcx.hir_node(tcx.local_def_id_to_hir_id(item.def_id.expect_local()))
334 && let hir::TraitItemKind::Type(_, None) = item.kind
335 {
336 false
337 } else {
338 true
339 }
340}
341
342fn min(vis1: ty::Visibility, vis2: ty::Visibility, tcx: TyCtxt<'_>) -> ty::Visibility {
343 if vis1.greater_than(vis2, tcx) { vis2 } else { vis1 }
344}
345
346struct FindMin<'a, 'tcx, VL: VisibilityLike, const SHALLOW: bool> {
348 tcx: TyCtxt<'tcx>,
349 effective_visibilities: &'a EffectiveVisibilities,
350 min: VL,
351}
352
353impl<'a, 'tcx, VL: VisibilityLike, const SHALLOW: bool> DefIdVisitor<'tcx>
354 for FindMin<'a, 'tcx, VL, SHALLOW>
355{
356 const SHALLOW: bool = SHALLOW;
357 fn skip_assoc_tys(&self) -> bool {
358 true
359 }
360 fn tcx(&self) -> TyCtxt<'tcx> {
361 self.tcx
362 }
363 fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) {
364 if let Some(def_id) = def_id.as_local() {
365 self.min = VL::new_min(self, def_id);
366 }
367 }
368}
369
370trait VisibilityLike: Sized {
371 const MAX: Self;
372 fn new_min<const SHALLOW: bool>(
373 find: &FindMin<'_, '_, Self, SHALLOW>,
374 def_id: LocalDefId,
375 ) -> Self;
376
377 fn of_impl<const SHALLOW: bool>(
380 def_id: LocalDefId,
381 of_trait: bool,
382 tcx: TyCtxt<'_>,
383 effective_visibilities: &EffectiveVisibilities,
384 ) -> Self {
385 let mut find = FindMin::<_, SHALLOW> { tcx, effective_visibilities, min: Self::MAX };
386 find.visit(tcx.type_of(def_id).instantiate_identity().skip_norm_wip());
387 if of_trait {
388 find.visit_trait(tcx.impl_trait_ref(def_id).instantiate_identity().skip_norm_wip());
389 }
390 find.min
391 }
392}
393
394impl VisibilityLike for ty::Visibility {
395 const MAX: Self = ty::Visibility::Public;
396 fn new_min<const SHALLOW: bool>(
397 find: &FindMin<'_, '_, Self, SHALLOW>,
398 def_id: LocalDefId,
399 ) -> Self {
400 min(find.tcx.local_visibility(def_id), find.min, find.tcx)
401 }
402}
403
404impl VisibilityLike for EffectiveVisibility {
405 const MAX: Self = EffectiveVisibility::from_vis(ty::Visibility::Public);
406 fn new_min<const SHALLOW: bool>(
407 find: &FindMin<'_, '_, Self, SHALLOW>,
408 def_id: LocalDefId,
409 ) -> Self {
410 let effective_vis =
411 find.effective_visibilities.effective_vis(def_id).copied().unwrap_or_else(|| {
412 let private_vis =
413 ty::Visibility::Restricted(find.tcx.parent_module_from_def_id(def_id));
414 EffectiveVisibility::from_vis(private_vis)
415 });
416
417 effective_vis.min(find.min, find.tcx)
418 }
419}
420
421type DefIdsToImpls = FxHashMap<LocalDefId, FxHashSet<LocalDefId>>;
422
423struct DefIdsToImplsCollector<'tcx, 'a> {
426 tcx: TyCtxt<'tcx>,
427 def_ids_to_impls: &'a mut DefIdsToImpls,
428 impl_def_id: LocalDefId,
429}
430
431impl<'tcx, 'a> DefIdsToImplsCollector<'tcx, 'a> {
432 fn collect(tcx: TyCtxt<'tcx>) -> DefIdsToImpls {
433 let mut def_ids_to_impls = Default::default();
434 for item in tcx.hir_free_items() {
435 let impl_def_id = item.owner_id.def_id;
436 let DefKind::Impl { of_trait } = tcx.def_kind(impl_def_id) else {
437 continue;
438 };
439
440 let mut visitor = DefIdsToImplsCollector {
442 tcx,
443 impl_def_id,
444 def_ids_to_impls: &mut def_ids_to_impls,
445 };
446
447 visitor.visit(tcx.type_of(impl_def_id).instantiate_identity().skip_norm_wip());
448 if of_trait {
449 visitor.visit_trait(
450 tcx.impl_trait_ref(impl_def_id).instantiate_identity().skip_norm_wip(),
451 );
452 }
453 }
454
455 def_ids_to_impls
456 }
457}
458
459impl<'tcx, 'a> DefIdVisitor<'tcx> for DefIdsToImplsCollector<'tcx, 'a> {
460 const SHALLOW: bool = true;
461 fn skip_assoc_tys(&self) -> bool {
462 true
463 }
464 fn tcx(&self) -> TyCtxt<'tcx> {
465 self.tcx
466 }
467 fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) {
468 if let Some(def_id) = def_id.as_local() {
469 if true {
{
match self.tcx.def_kind(def_id) {
DefKind::Enum | DefKind::Union | DefKind::Struct |
DefKind::ForeignTy | DefKind::Trait => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::Enum | DefKind::Union | DefKind::Struct | DefKind::ForeignTy |\nDefKind::Trait",
::core::option::Option::None);
}
}
};
};debug_assert_matches!(
470 self.tcx.def_kind(def_id),
471 DefKind::Enum
472 | DefKind::Union
473 | DefKind::Struct
474 | DefKind::ForeignTy
475 | DefKind::Trait
476 );
477 self.def_ids_to_impls.entry(def_id).or_default().insert(self.impl_def_id);
478 }
479 }
480}
481
482struct EmbargoVisitor<'tcx> {
484 tcx: TyCtxt<'tcx>,
485 effective_visibilities: EffectiveVisibilities,
487 queue: IndexSet<LocalDefId>,
489 def_ids_to_impls: DefIdsToImpls,
491}
492
493struct ReachEverythingInTheInterfaceVisitor<'a, 'tcx> {
494 effective_vis: EffectiveVisibility,
495 item_def_id: LocalDefId,
496 ev: &'a mut EmbargoVisitor<'tcx>,
497 level: Level,
498}
499
500impl<'tcx> EmbargoVisitor<'tcx> {
501 fn get(&self, def_id: LocalDefId) -> Option<EffectiveVisibility> {
502 self.effective_visibilities.effective_vis(def_id).copied()
503 }
504
505 fn update(
507 &mut self,
508 def_id: LocalDefId,
509 inherited_effective_vis: EffectiveVisibility,
510 level: Level,
511 ) {
512 let nominal_vis = self.tcx.local_visibility(def_id);
513 self.update_eff_vis(def_id, inherited_effective_vis, Some(nominal_vis), level);
514 }
515
516 fn update_eff_vis(
517 &mut self,
518 def_id: LocalDefId,
519 inherited_effective_vis: EffectiveVisibility,
520 max_vis: Option<ty::Visibility>,
521 level: Level,
522 ) -> bool {
523 let private_vis = ty::Visibility::Restricted(self.tcx.parent_module_from_def_id(def_id));
524 if max_vis != Some(private_vis) {
525 return self.effective_visibilities.update(
526 def_id,
527 max_vis,
528 private_vis,
529 inherited_effective_vis,
530 level,
531 self.tcx,
532 );
533 }
534 false
535 }
536
537 fn reach(
538 &mut self,
539 def_id: LocalDefId,
540 effective_vis: EffectiveVisibility,
541 ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
542 ReachEverythingInTheInterfaceVisitor {
543 effective_vis,
544 item_def_id: def_id,
545 ev: self,
546 level: Level::Reachable,
547 }
548 }
549
550 fn reach_through_impl_trait(
551 &mut self,
552 def_id: LocalDefId,
553 effective_vis: EffectiveVisibility,
554 ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
555 ReachEverythingInTheInterfaceVisitor {
556 effective_vis,
557 item_def_id: def_id,
558 ev: self,
559 level: Level::ReachableThroughImplTrait,
560 }
561 }
562}
563
564impl<'tcx> EmbargoVisitor<'tcx> {
565 fn check_assoc_item(&mut self, item: &ty::AssocItem, item_ev: EffectiveVisibility) {
566 let def_id = item.def_id.expect_local();
567 let tcx = self.tcx;
568 let mut reach = self.reach(def_id, item_ev);
569 reach.generics().clauses();
570 if assoc_has_type_of(tcx, item) {
571 reach.ty();
572 }
573 if item.is_type() && item.container == AssocContainer::Trait {
574 reach.bounds();
575 }
576 }
577
578 fn check_def_id(&mut self, def_id: LocalDefId) {
579 let item_ev = self.get(def_id);
582 let def_kind = self.tcx.def_kind(def_id);
583 match def_kind {
584 DefKind::Use
586 | DefKind::ExternCrate
587 | DefKind::GlobalAsm
588 | DefKind::TestBinderConstraints => {}
589 DefKind::Mod => {}
591 DefKind::Macro { .. } => {}
593 DefKind::ForeignTy
594 | DefKind::Const
595 | DefKind::Static { .. }
596 | DefKind::Fn
597 | DefKind::TyAlias => {
598 if let Some(item_ev) = item_ev {
599 self.reach(def_id, item_ev).generics().clauses().ty();
600 }
601 }
602 DefKind::Trait => {
603 if let Some(item_ev) = item_ev {
604 self.reach(def_id, item_ev).generics().clauses();
605
606 for assoc_item in self.tcx.associated_items(def_id).in_definition_order() {
607 let def_id = assoc_item.def_id.expect_local();
608 self.update(def_id, item_ev, Level::Reachable);
609
610 self.check_assoc_item(assoc_item, item_ev);
611 }
612 }
613 }
614 DefKind::TraitAlias => {
615 if let Some(item_ev) = item_ev {
616 self.reach(def_id, item_ev).generics().clauses();
617 }
618 }
619 DefKind::Impl { of_trait } => {
620 let item_ev = EffectiveVisibility::of_impl::<true>(
631 def_id,
632 of_trait,
633 self.tcx,
634 &self.effective_visibilities,
635 );
636
637 self.update_eff_vis(def_id, item_ev, None, Level::Direct);
638
639 {
640 let mut reach = self.reach(def_id, item_ev);
641 reach.generics().clauses().ty();
642 if of_trait {
643 reach.trait_ref();
644 }
645 }
646
647 for assoc_item in self.tcx.associated_items(def_id).in_definition_order() {
648 let def_id = assoc_item.def_id.expect_local();
649 let max_vis =
650 if of_trait { None } else { Some(self.tcx.local_visibility(def_id)) };
651 self.update_eff_vis(def_id, item_ev, max_vis, Level::Direct);
652
653 if let Some(impl_item_ev) = self.get(def_id) {
654 self.check_assoc_item(assoc_item, impl_item_ev);
655 }
656 }
657 }
658 DefKind::Enum => {
659 if let Some(item_ev) = item_ev {
660 self.reach(def_id, item_ev).generics().clauses();
661 }
662 let def = self.tcx.adt_def(def_id);
663 for variant in def.variants() {
664 if let Some(item_ev) = item_ev {
665 self.update(variant.def_id.expect_local(), item_ev, Level::Reachable);
666 }
667
668 if let Some(variant_ev) = self.get(variant.def_id.expect_local()) {
669 if let Some(ctor_def_id) = variant.ctor_def_id() {
670 self.update(ctor_def_id.expect_local(), variant_ev, Level::Reachable);
671 }
672
673 for field in &variant.fields {
674 let field = field.did.expect_local();
675 self.update(field, variant_ev, Level::Reachable);
676 self.reach(field, variant_ev).ty();
677 }
678 self.reach(def_id, variant_ev).ty();
681 }
682 if let Some(ctor_def_id) = variant.ctor_def_id() {
683 if let Some(ctor_ev) = self.get(ctor_def_id.expect_local()) {
684 self.reach(def_id, ctor_ev).ty();
685 }
686 }
687 }
688 }
689 DefKind::Struct | DefKind::Union => {
690 let def = self.tcx.adt_def(def_id).non_enum_variant();
691 if let Some(item_ev) = item_ev {
692 self.reach(def_id, item_ev).generics().clauses();
693 for field in &def.fields {
694 let field = field.did.expect_local();
695 self.update(field, item_ev, Level::Reachable);
696 if let Some(field_ev) = self.get(field) {
697 self.reach(field, field_ev).ty();
698 }
699 }
700 }
701 if let Some(ctor_def_id) = def.ctor_def_id() {
702 if let Some(item_ev) = item_ev {
703 self.update(ctor_def_id.expect_local(), item_ev, Level::Reachable);
704 }
705 if let Some(ctor_ev) = self.get(ctor_def_id.expect_local()) {
706 self.reach(def_id, ctor_ev).ty();
707 }
708 }
709 }
710 DefKind::ForeignMod => {}
712 DefKind::Field
713 | DefKind::Variant
714 | DefKind::AssocFn
715 | DefKind::AssocTy
716 | DefKind::AssocConst
717 | DefKind::TyParam
718 | DefKind::AnonConst
719 | DefKind::OpaqueTy
720 | DefKind::Closure
721 | DefKind::SyntheticCoroutineBody
722 | DefKind::ConstParam
723 | DefKind::LifetimeParam
724 | DefKind::Ctor(..) => {
725 ::rustc_span::macros::bug_impl(Some(self.tcx.def_span(def_id)),
format_args!("{0:?} should be checked while checking parent", def_kind),
Location::caller())span_bug!(
726 self.tcx.def_span(def_id),
727 "{def_kind:?} should be checked while checking parent"
728 )
729 }
730 }
731 }
732}
733
734impl ReachEverythingInTheInterfaceVisitor<'_, '_> {
735 fn generics(&mut self) -> &mut Self {
736 for param in &self.ev.tcx.generics_of(self.item_def_id).own_params {
737 if let GenericParamDefKind::Const { .. } = param.kind {
738 self.visit(
739 self.ev.tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip(),
740 );
741 }
742 if let Some(default) = param.default_value(self.ev.tcx) {
743 self.visit(default.instantiate_identity().skip_norm_wip());
744 }
745 }
746 self
747 }
748
749 fn clauses(&mut self) -> &mut Self {
750 self.visit_gen_clauses(self.ev.tcx.explicit_clauses_of(self.item_def_id));
751 self
752 }
753
754 fn bounds(&mut self) -> &mut Self {
755 self.visit_clauses(self.ev.tcx.explicit_item_bounds(self.item_def_id).skip_binder());
756 self
757 }
758
759 fn ty(&mut self) -> &mut Self {
760 self.visit(self.ev.tcx.type_of(self.item_def_id).instantiate_identity().skip_norm_wip());
761 self
762 }
763
764 fn trait_ref(&mut self) -> &mut Self {
765 self.visit_trait(
766 self.ev.tcx.impl_trait_ref(self.item_def_id).instantiate_identity().skip_norm_wip(),
767 );
768 self
769 }
770
771 fn enqueue_def_id(&mut self, def_id: LocalDefId) {
774 let def_kind = self.ev.tcx.def_kind(def_id);
775 match def_kind {
776 DefKind::Enum
777 | DefKind::Union
778 | DefKind::Struct
779 | DefKind::ForeignTy
780 | DefKind::Trait => {
781 self.ev.queue.insert(def_id);
782 if let Some(impls) = self.ev.def_ids_to_impls.get(&def_id) {
784 #[allow(rustc::potential_query_instability)]
786 self.ev.queue.extend(impls);
787 }
788 }
789
790 DefKind::TraitAlias | DefKind::Fn | DefKind::TyAlias => {
791 self.ev.queue.insert(def_id);
792 }
793
794 DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy => {
795 self.ev.queue.insert(self.ev.tcx.local_parent(def_id));
797 }
798
799 DefKind::Ctor(ctor_of, _) => {
800 let update_id = match ctor_of {
801 CtorOf::Struct => self.ev.tcx.local_parent(def_id),
802 CtorOf::Variant => self.ev.tcx.local_parent(self.ev.tcx.local_parent(def_id)),
803 };
804 self.ev.queue.insert(update_id);
806 }
807
808 DefKind::Closure => {}
811
812 DefKind::Impl { .. }
814 | DefKind::Field
815 | DefKind::Variant
816 | DefKind::Static { .. }
817 | DefKind::Macro(_)
818 | DefKind::TyParam
819 | DefKind::AnonConst
820 | DefKind::OpaqueTy
821 | DefKind::SyntheticCoroutineBody
822 | DefKind::ConstParam
823 | DefKind::LifetimeParam
824 | DefKind::Mod
825 | DefKind::Use
826 | DefKind::ExternCrate
827 | DefKind::GlobalAsm
828 | DefKind::ForeignMod
829 | DefKind::Const
830 | DefKind::TestBinderConstraints => {
831 ::rustc_span::macros::bug_impl(Some(self.tcx().def_span(def_id)),
format_args!("{0:?} unexpectedly reached by `ReachEverythingInTheInterfaceVisitor`",
def_kind), Location::caller())span_bug!(
832 self.tcx().def_span(def_id),
833 "{def_kind:?} unexpectedly reached by `ReachEverythingInTheInterfaceVisitor`"
834 )
835 }
836 }
837 }
838}
839
840impl<'tcx> DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
841 fn tcx(&self) -> TyCtxt<'tcx> {
842 self.ev.tcx
843 }
844 fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) {
845 if let Some(def_id) = def_id.as_local() {
846 let max_vis = (self.level != Level::ReachableThroughImplTrait)
854 .then(|| self.ev.tcx.local_visibility(def_id));
855 if self.ev.update_eff_vis(def_id, self.effective_vis, max_vis, self.level) {
856 self.enqueue_def_id(def_id);
857 }
858 }
859 }
860}
861
862pub struct TestReachabilityVisitor<'a, 'tcx> {
864 tcx: TyCtxt<'tcx>,
865 effective_visibilities: &'a EffectiveVisibilities,
866}
867
868impl<'a, 'tcx> TestReachabilityVisitor<'a, 'tcx> {
869 fn effective_visibility_diagnostic(&self, def_id: LocalDefId) {
870 if {
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(def_id, &self.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcEffectiveVisibility)
=> {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(self.tcx, def_id, RustcEffectiveVisibility) {
871 let mut error_msg = String::new();
872 let span = self.tcx.def_span(def_id.to_def_id());
873 if let Some(effective_vis) = self.effective_visibilities.effective_vis(def_id) {
874 for level in Level::all_levels() {
875 let vis_str = effective_vis.at_level(level).to_string(def_id, self.tcx);
876 if level != Level::Direct {
877 error_msg.push_str(", ");
878 }
879 error_msg.push_str(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}: {1}", level, vis_str))
})format!("{level:?}: {vis_str}"));
880 }
881 } else {
882 error_msg.push_str("not in the table");
883 }
884 self.tcx.dcx().emit_err(ReportEffectiveVisibility { span, descr: error_msg });
885 }
886 }
887}
888
889impl<'a, 'tcx> TestReachabilityVisitor<'a, 'tcx> {
890 fn check_def_id(&self, owner_id: OwnerId) {
891 self.effective_visibility_diagnostic(owner_id.def_id);
892
893 match self.tcx.def_kind(owner_id) {
894 DefKind::Enum => {
895 let def = self.tcx.adt_def(owner_id.def_id);
896 for variant in def.variants() {
897 self.effective_visibility_diagnostic(variant.def_id.expect_local());
898 if let Some(ctor_def_id) = variant.ctor_def_id() {
899 self.effective_visibility_diagnostic(ctor_def_id.expect_local());
900 }
901 for field in &variant.fields {
902 self.effective_visibility_diagnostic(field.did.expect_local());
903 }
904 }
905 }
906 DefKind::Struct | DefKind::Union => {
907 let def = self.tcx.adt_def(owner_id.def_id).non_enum_variant();
908 if let Some(ctor_def_id) = def.ctor_def_id() {
909 self.effective_visibility_diagnostic(ctor_def_id.expect_local());
910 }
911 for field in &def.fields {
912 self.effective_visibility_diagnostic(field.did.expect_local());
913 }
914 }
915 _ => {}
916 }
917 }
918}
919
920struct NamePrivacyVisitor<'tcx> {
926 tcx: TyCtxt<'tcx>,
927 mod_id: LocalModId,
928 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
929}
930
931impl<'tcx> NamePrivacyVisitor<'tcx> {
932 #[track_caller]
936 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
937 self.maybe_typeck_results
938 .expect("`NamePrivacyVisitor::typeck_results` called outside of body")
939 }
940
941 fn check_field(
943 &self,
944 use_ctxt: Span, def: ty::AdtDef<'tcx>, field: &'tcx ty::FieldDef,
947 ) -> bool {
948 if def.is_enum() {
949 return true;
950 }
951
952 let ident = Ident::new(sym::dummy, use_ctxt);
954 let (_, def_id) = self.tcx.adjust_ident_and_get_scope(ident, def.did(), self.mod_id);
955 !field.vis.is_accessible_from(def_id, self.tcx)
956 }
957
958 fn emit_unreachable_field_error(
960 &self,
961 fields: Vec<(Symbol, Span, bool )>,
962 def: ty::AdtDef<'tcx>, update_syntax: Option<Span>,
964 struct_span: Span,
965 ) {
966 if def.is_enum() || fields.is_empty() {
967 return;
968 }
969
970 let Some(field_names) = listify(&fields[..], |(n, _, _)| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", n))
})format!("`{n}`")) else { return };
982 let span: MultiSpan = fields.iter().map(|(_, span, _)| *span).collect::<Vec<Span>>().into();
983
984 let rest_field_names: Vec<_> =
986 fields.iter().filter(|(_, _, is_present)| !is_present).map(|(n, _, _)| n).collect();
987 let rest_len = rest_field_names.len();
988 let rest_field_names =
989 listify(&rest_field_names[..], |n| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", n))
})format!("`{n}`")).unwrap_or_default();
990 let labels = fields
992 .iter()
993 .filter(|(_, _, is_present)| *is_present)
994 .map(|(_, span, _)| FieldIsPrivateLabel::Other { span: *span })
995 .chain(update_syntax.iter().map(|span| FieldIsPrivateLabel::IsUpdateSyntax {
996 span: *span,
997 rest_field_names: rest_field_names.clone(),
998 rest_len,
999 }))
1000 .collect();
1001
1002 self.tcx.dcx().emit_err(FieldIsPrivate {
1003 span,
1004 struct_span: if self
1005 .tcx
1006 .sess
1007 .source_map()
1008 .is_multiline(fields[0].1.between(struct_span))
1009 {
1010 Some(struct_span)
1011 } else {
1012 None
1013 },
1014 field_names,
1015 variant_descr: def.variant_descr(),
1016 def_path_str: self.tcx.def_path_str(def.did()),
1017 labels,
1018 len: fields.len(),
1019 });
1020 }
1021
1022 fn check_expanded_fields(
1023 &self,
1024 adt: ty::AdtDef<'tcx>,
1025 variant: &'tcx ty::VariantDef,
1026 fields: &[hir::ExprField<'tcx>],
1027 span: Span,
1028 struct_span: Span,
1029 ) {
1030 let mut failed_fields = ::alloc::vec::Vec::new()vec![];
1031 for (vf_index, variant_field) in variant.fields.iter_enumerated() {
1032 let field =
1033 fields.iter().find(|f| self.typeck_results().field_index(f.hir_id) == vf_index);
1034 let (use_ctxt, span) = match field {
1035 Some(field) => (field.ident.span, field.span),
1036 None => (span, span),
1037 };
1038 if self.check_field(use_ctxt, adt, variant_field) {
1039 let name = match field {
1040 Some(field) => field.ident.name,
1041 None => variant_field.name,
1042 };
1043 failed_fields.push((name, span, field.is_some()));
1044 }
1045 }
1046 self.emit_unreachable_field_error(failed_fields, adt, Some(span), struct_span);
1047 }
1048}
1049
1050impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> {
1051 fn visit_nested_body(&mut self, body_id: hir::BodyId) {
1052 let new_typeck_results = self.tcx.typeck_body(body_id);
1053 if new_typeck_results.tainted_by_errors.is_some() {
1055 return;
1056 }
1057 let old_maybe_typeck_results = self.maybe_typeck_results.replace(new_typeck_results);
1058 self.visit_body(self.tcx.hir_body(body_id));
1059 self.maybe_typeck_results = old_maybe_typeck_results;
1060 }
1061
1062 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1063 if let hir::ExprKind::Struct(qpath, fields, ref base) = expr.kind {
1064 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
1065 let adt = self.typeck_results().expr_ty(expr).ty_adt_def().unwrap();
1066 let variant = adt.variant_of_res(res);
1067 match *base {
1068 hir::StructTailExpr::Base(base) => {
1069 self.check_expanded_fields(adt, variant, fields, base.span, qpath.span());
1073 }
1074 hir::StructTailExpr::DefaultFields(span) => {
1075 self.check_expanded_fields(adt, variant, fields, span, qpath.span());
1076 }
1077 hir::StructTailExpr::None | hir::StructTailExpr::NoneWithError(_) => {
1078 let mut failed_fields = ::alloc::vec::Vec::new()vec![];
1079 for field in fields {
1080 let index = self.typeck_results().field_index(field.hir_id);
1081 if self.check_field(field.ident.span, adt, &variant.fields[index]) {
1082 let name = match field.ident.name {
1086 kw::Underscore => variant.fields[index].name,
1087 name => name,
1088 };
1089 failed_fields.push((name, field.ident.span, true));
1090 }
1091 }
1092 self.emit_unreachable_field_error(failed_fields, adt, None, qpath.span());
1093 }
1094 }
1095 }
1096
1097 intravisit::walk_expr(self, expr);
1098 }
1099
1100 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
1101 if let PatKind::Struct(ref qpath, fields, _) = pat.kind {
1102 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
1103 let adt = self.typeck_results().pat_ty(pat).ty_adt_def().unwrap();
1104 let variant = adt.variant_of_res(res);
1105 let mut failed_fields = ::alloc::vec::Vec::new()vec![];
1106 for field in fields {
1107 let index = self.typeck_results().field_index(field.hir_id);
1108 if self.check_field(field.ident.span, adt, &variant.fields[index]) {
1109 failed_fields.push((field.ident.name, field.ident.span, true));
1110 }
1111 }
1112 self.emit_unreachable_field_error(failed_fields, adt, None, qpath.span());
1113 }
1114
1115 intravisit::walk_pat(self, pat);
1116 }
1117}
1118
1119struct TypePrivacyVisitor<'tcx> {
1124 tcx: TyCtxt<'tcx>,
1125 mod_id: LocalModId,
1126 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
1127 span: Span,
1128 accessible_tys: FxHashSet<Ty<'tcx>>,
1133}
1134
1135impl<'tcx> TypePrivacyVisitor<'tcx> {
1136 fn item_is_accessible(&self, did: DefId) -> bool {
1137 self.tcx.visibility(did).is_accessible_from(self.mod_id, self.tcx)
1138 }
1139
1140 fn check_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<()> {
1141 if self.accessible_tys.contains(&ty) {
1142 return ControlFlow::Continue(());
1143 }
1144 self.visit(ty)?;
1145 self.accessible_tys.insert(ty);
1146 ControlFlow::Continue(())
1147 }
1148
1149 fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
1151 self.span = span;
1152 let typeck_results = self
1153 .maybe_typeck_results
1154 .unwrap_or_else(|| ::rustc_span::macros::bug_impl(Some(span),
format_args!("`hir::Expr` or `hir::Pat` outside of a body"),
Location::caller())span_bug!(span, "`hir::Expr` or `hir::Pat` outside of a body"));
1155 try {
1156 self.check_ty(typeck_results.node_type(id))?;
1157 self.visit(typeck_results.node_args(id))?;
1158 if let Some(adjustments) = typeck_results.adjustments().get(id) {
1159 adjustments.iter().try_for_each(|adjustment| self.check_ty(adjustment.target))?;
1160 }
1161 }
1162 .is_break()
1163 }
1164
1165 fn check_def_id(&self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1166 let is_error = !self.item_is_accessible(def_id);
1167 if is_error {
1168 self.tcx.dcx().emit_err(ItemIsPrivate { span: self.span, kind, descr: descr.into() });
1169 }
1170 is_error
1171 }
1172}
1173
1174impl<'tcx> rustc_ty_walk::SpannedTypeVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1175 type Result = ControlFlow<()>;
1176 fn visit(&mut self, span: Span, value: impl TypeVisitable<TyCtxt<'tcx>>) -> Self::Result {
1177 self.span = span;
1178 value.visit_with(&mut self.skeleton())
1179 }
1180}
1181
1182impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> {
1183 fn visit_nested_body(&mut self, body_id: hir::BodyId) {
1184 let old_maybe_typeck_results =
1185 self.maybe_typeck_results.replace(self.tcx.typeck_body(body_id));
1186 self.visit_body(self.tcx.hir_body(body_id));
1187 self.maybe_typeck_results = old_maybe_typeck_results;
1188 }
1189
1190 fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx, AmbigArg>) {
1191 self.span = hir_ty.span;
1192 let ty = self
1193 .maybe_typeck_results
1194 .unwrap_or_else(|| ::rustc_span::macros::bug_impl(Some(hir_ty.span),
format_args!("`hir::Ty` outside of a body"), Location::caller())span_bug!(hir_ty.span, "`hir::Ty` outside of a body"))
1195 .node_type(hir_ty.hir_id);
1196 if self.check_ty(ty).is_break() {
1197 return;
1198 }
1199
1200 intravisit::walk_ty(self, hir_ty);
1201 }
1202
1203 fn visit_infer(
1204 &mut self,
1205 inf_id: rustc_hir::HirId,
1206 inf_span: Span,
1207 _kind: InferKind<'tcx>,
1208 ) -> Self::Result {
1209 self.span = inf_span;
1210 if let Some(ty) = self
1211 .maybe_typeck_results
1212 .unwrap_or_else(|| ::rustc_span::macros::bug_impl(Some(inf_span),
format_args!("Inference variable outside of a body"), Location::caller())span_bug!(inf_span, "Inference variable outside of a body"))
1213 .node_type_opt(inf_id)
1214 {
1215 if self.check_ty(ty).is_break() {
1216 return;
1217 }
1218 } else {
1219 }
1221
1222 self.visit_id(inf_id)
1223 }
1224
1225 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1227 if self.check_expr_pat_type(expr.hir_id, expr.span) {
1228 return;
1230 }
1231 match expr.kind {
1232 hir::ExprKind::Assign(_, rhs, _) | hir::ExprKind::Match(rhs, ..) => {
1233 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
1235 return;
1236 }
1237 }
1238 hir::ExprKind::MethodCall(segment, ..) => {
1239 self.span = segment.ident.span;
1241 let typeck_results = self
1242 .maybe_typeck_results
1243 .unwrap_or_else(|| ::rustc_span::macros::bug_impl(Some(self.span),
format_args!("`hir::Expr` outside of a body"), Location::caller())span_bug!(self.span, "`hir::Expr` outside of a body"));
1244 if let Some(def_id) = typeck_results.type_dependent_def_id(expr.hir_id) {
1245 if self
1246 .check_ty(self.tcx.type_of(def_id).instantiate_identity().skip_norm_wip())
1247 .is_break()
1248 {
1249 return;
1250 }
1251 } else {
1252 self.tcx
1253 .dcx()
1254 .span_delayed_bug(expr.span, "no type-dependent def for method call");
1255 }
1256 }
1257 _ => {}
1258 }
1259
1260 intravisit::walk_expr(self, expr);
1261 }
1262
1263 fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) {
1270 let def = match qpath {
1271 hir::QPath::Resolved(_, path) => match path.res {
1272 Res::Def(kind, def_id) => Some((kind, def_id)),
1273 _ => None,
1274 },
1275 hir::QPath::TypeRelative(..) => {
1276 match self.maybe_typeck_results {
1277 Some(typeck_results) => typeck_results.type_dependent_def(id),
1278 None => None,
1280 }
1281 }
1282 };
1283 let def = def.filter(|(kind, _)| {
1284 #[allow(non_exhaustive_omitted_patterns)] match kind {
DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy |
DefKind::Static { .. } => true,
_ => false,
}matches!(
1285 kind,
1286 DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static { .. }
1287 )
1288 });
1289 if let Some((kind, def_id)) = def {
1290 let is_local_static =
1291 if let DefKind::Static { .. } = kind { def_id.is_local() } else { false };
1292 if !self.item_is_accessible(def_id) && !is_local_static {
1293 let name = match *qpath {
1294 hir::QPath::Resolved(_, path) => Some(self.tcx.def_path_str(path.res.def_id())),
1295 hir::QPath::TypeRelative(_, segment) => Some(segment.ident.to_string()),
1296 };
1297 let kind = self.tcx.def_descr(def_id);
1298 let sess = self.tcx.sess;
1299 let _ = match name {
1300 Some(name) => {
1301 sess.dcx().emit_err(ItemIsPrivate { span, kind, descr: (&name).into() })
1302 }
1303 None => sess.dcx().emit_err(UnnamedItemIsPrivate { span, kind }),
1304 };
1305 return;
1306 }
1307 }
1308
1309 intravisit::walk_qpath(self, qpath, id);
1310 }
1311
1312 fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) {
1314 if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
1315 return;
1317 }
1318
1319 intravisit::walk_pat(self, pattern);
1320 }
1321
1322 fn visit_local(&mut self, local: &'tcx hir::LetStmt<'tcx>) {
1323 if let Some(init) = local.init {
1324 if self.check_expr_pat_type(init.hir_id, init.span) {
1325 return;
1327 }
1328 }
1329
1330 intravisit::walk_local(self, local);
1331 }
1332}
1333
1334impl<'tcx> DefIdVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1335 type Result = ControlFlow<()>;
1336 fn tcx(&self) -> TyCtxt<'tcx> {
1337 self.tcx
1338 }
1339 fn visit_def_id(
1340 &mut self,
1341 def_id: DefId,
1342 kind: &str,
1343 descr: &dyn fmt::Display,
1344 ) -> Self::Result {
1345 if self.check_def_id(def_id, kind, descr) {
1346 ControlFlow::Break(())
1347 } else {
1348 ControlFlow::Continue(())
1349 }
1350 }
1351}
1352
1353struct SearchInterfaceForPrivateItemsVisitor<'tcx> {
1359 tcx: TyCtxt<'tcx>,
1360 item_def_id: LocalDefId,
1361 required_visibility: ty::Visibility,
1363 required_effective_vis: Option<EffectiveVisibility>,
1364 hard_error: bool = false,
1365 in_primary_interface: bool = true,
1366 skip_assoc_tys: bool = false,
1367}
1368
1369impl SearchInterfaceForPrivateItemsVisitor<'_> {
1370 fn generics(&mut self) -> &mut Self {
1371 self.in_primary_interface = true;
1372 for param in &self.tcx.generics_of(self.item_def_id).own_params {
1373 if let GenericParamDefKind::Const { .. } = param.kind {
1374 let _ = self
1375 .visit(self.tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip());
1376 }
1377 if let Some(default) = param.default_value(self.tcx) {
1378 let _ = self.visit(default.instantiate_identity().skip_norm_wip());
1379 }
1380 }
1381 self
1382 }
1383
1384 fn clauses(&mut self) -> &mut Self {
1385 self.in_primary_interface = false;
1386 let _ = self.visit_gen_clauses(self.tcx.explicit_clauses_of(self.item_def_id));
1393 self
1394 }
1395
1396 fn bounds(&mut self) -> &mut Self {
1397 self.in_primary_interface = false;
1398 let _ = self.visit_clauses(self.tcx.explicit_item_bounds(self.item_def_id).skip_binder());
1399 self
1400 }
1401
1402 fn ty(&mut self) -> &mut Self {
1403 self.in_primary_interface = true;
1404 let _ =
1405 self.visit(self.tcx.type_of(self.item_def_id).instantiate_identity().skip_norm_wip());
1406 self
1407 }
1408
1409 fn trait_ref(&mut self) -> &mut Self {
1410 self.in_primary_interface = true;
1411 let _ = self.visit_trait(
1412 self.tcx.impl_trait_ref(self.item_def_id).instantiate_identity().skip_norm_wip(),
1413 );
1414 self
1415 }
1416
1417 fn check_def_id(&self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1418 if self.leaks_private_dep(def_id) {
1419 self.tcx.emit_node_span_lint(
1420 EXPORTED_PRIVATE_DEPENDENCIES,
1421 self.tcx.local_def_id_to_hir_id(self.item_def_id),
1422 self.tcx.def_span(self.item_def_id.to_def_id()),
1423 FromPrivateDependencyInPublicInterface {
1424 kind,
1425 descr: descr.into(),
1426 krate: self.tcx.crate_name(def_id.krate),
1427 },
1428 );
1429 }
1430
1431 let Some(local_def_id) = def_id.as_local() else {
1432 return false;
1433 };
1434
1435 let vis = self.tcx.local_visibility(local_def_id);
1436 if self.hard_error && self.required_visibility.greater_than(vis, self.tcx) {
1437 let vis_descr = match vis {
1438 ty::Visibility::Public => "public",
1439 ty::Visibility::Restricted(vis_mod_id) => {
1440 if vis_mod_id == self.tcx.parent_module_from_def_id(local_def_id) {
1441 "private"
1442 } else if vis_mod_id.is_top_level_module() {
1443 "crate-private"
1444 } else {
1445 "restricted"
1446 }
1447 }
1448 };
1449
1450 let span = self.tcx.def_span(self.item_def_id.to_def_id());
1451 let vis_span = self.tcx.def_span(def_id);
1452 self.tcx.dcx().emit_err(InPublicInterface {
1453 span,
1454 vis_descr,
1455 kind,
1456 descr: descr.into(),
1457 vis_span,
1458 });
1459 return false;
1460 }
1461
1462 let Some(effective_vis) = self.required_effective_vis else {
1463 return false;
1464 };
1465
1466 let reachable_at_vis = *effective_vis.at_level(Level::Reachable);
1467
1468 if reachable_at_vis.greater_than(vis, self.tcx) {
1469 let lint = if self.in_primary_interface { PRIVATE_INTERFACES } else { PRIVATE_BOUNDS };
1470 let span = self.tcx.def_span(self.item_def_id.to_def_id());
1471 let vis_span = self.tcx.def_span(def_id);
1472 self.tcx.emit_node_span_lint(
1473 lint,
1474 self.tcx.local_def_id_to_hir_id(self.item_def_id),
1475 span,
1476 PrivateInterfacesOrBoundsLint {
1477 item_span: span,
1478 item_kind: self.tcx.def_descr(self.item_def_id.to_def_id()),
1479 item_descr: (&LazyDefPathStr {
1480 def_id: self.item_def_id.to_def_id(),
1481 tcx: self.tcx,
1482 })
1483 .into(),
1484 item_vis_descr: &reachable_at_vis.to_string(self.item_def_id, self.tcx),
1485 ty_span: vis_span,
1486 ty_kind: kind,
1487 ty_descr: descr.into(),
1488 ty_vis_descr: &vis.to_string(local_def_id, self.tcx),
1489 },
1490 );
1491 }
1492
1493 false
1494 }
1495
1496 fn leaks_private_dep(&self, item_id: DefId) -> bool {
1501 let ret = self.required_visibility.is_public() && self.tcx.is_private_dep(item_id.krate);
1502
1503 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_privacy/src/lib.rs:1503",
"rustc_privacy", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_privacy/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(1503u32),
::tracing_core::__macro_support::Option::Some("rustc_privacy"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("leaks_private_dep(item_id={0:?})={1}",
item_id, ret) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("leaks_private_dep(item_id={:?})={}", item_id, ret);
1504 ret
1505 }
1506}
1507
1508impl<'tcx> DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> {
1509 type Result = ControlFlow<()>;
1510 fn skip_assoc_tys(&self) -> bool {
1511 self.skip_assoc_tys
1512 }
1513 fn tcx(&self) -> TyCtxt<'tcx> {
1514 self.tcx
1515 }
1516 fn visit_def_id(
1517 &mut self,
1518 def_id: DefId,
1519 kind: &str,
1520 descr: &dyn fmt::Display,
1521 ) -> Self::Result {
1522 if self.check_def_id(def_id, kind, descr) {
1523 ControlFlow::Break(())
1524 } else {
1525 ControlFlow::Continue(())
1526 }
1527 }
1528}
1529
1530struct PrivateItemsInPublicInterfacesChecker<'a, 'tcx> {
1531 tcx: TyCtxt<'tcx>,
1532 effective_visibilities: &'a EffectiveVisibilities,
1533}
1534
1535impl<'tcx> PrivateItemsInPublicInterfacesChecker<'_, 'tcx> {
1536 fn check(
1537 &self,
1538 def_id: LocalDefId,
1539 required_visibility: ty::Visibility,
1540 required_effective_vis: Option<EffectiveVisibility>,
1541 ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> {
1542 SearchInterfaceForPrivateItemsVisitor {
1543 tcx: self.tcx,
1544 item_def_id: def_id,
1545 required_visibility,
1546 required_effective_vis,
1547 ..
1548 }
1549 }
1550
1551 fn check_unnameable(&self, def_id: LocalDefId, effective_vis: Option<EffectiveVisibility>) {
1552 let Some(effective_vis) = effective_vis else {
1553 return;
1554 };
1555
1556 let reexported_at_vis = effective_vis.at_level(Level::Reexported);
1557 let reachable_at_vis = effective_vis.at_level(Level::Reachable);
1558
1559 if reachable_at_vis.is_public() && reexported_at_vis != reachable_at_vis {
1560 let hir_id = self.tcx.local_def_id_to_hir_id(def_id);
1561 let span = self.tcx.def_span(def_id.to_def_id());
1562 self.tcx.emit_node_span_lint(
1563 UNNAMEABLE_TYPES,
1564 hir_id,
1565 span,
1566 UnnameableTypesLint {
1567 span,
1568 kind: self.tcx.def_descr(def_id.to_def_id()),
1569 descr: (&LazyDefPathStr { def_id: def_id.to_def_id(), tcx: self.tcx }).into(),
1570 reachable_vis: &reachable_at_vis.to_string(def_id, self.tcx),
1571 reexported_vis: &reexported_at_vis.to_string(def_id, self.tcx),
1572 },
1573 );
1574 }
1575 }
1576
1577 fn check_assoc_item(
1578 &self,
1579 item: &ty::AssocItem,
1580 vis: ty::Visibility,
1581 effective_vis: Option<EffectiveVisibility>,
1582 ) {
1583 let mut check = self.check(item.def_id.expect_local(), vis, effective_vis);
1584
1585 let is_assoc_ty = item.is_type();
1586 check.hard_error = is_assoc_ty;
1587 check.generics().clauses();
1588 if assoc_has_type_of(self.tcx, item) {
1589 check.ty();
1590 }
1591 if is_assoc_ty && item.container == AssocContainer::Trait {
1592 check.hard_error = false;
1595 check.bounds();
1596 }
1597 }
1598
1599 fn get(&self, def_id: LocalDefId) -> Option<EffectiveVisibility> {
1600 self.effective_visibilities.effective_vis(def_id).copied()
1601 }
1602
1603 fn check_item(&self, id: ItemId) {
1604 let tcx = self.tcx;
1605 let def_id = id.owner_id.def_id;
1606 let item_visibility = tcx.local_visibility(def_id);
1607 let effective_vis = self.get(def_id);
1608 let def_kind = tcx.def_kind(def_id);
1609
1610 match def_kind {
1611 DefKind::Const | DefKind::Static { .. } | DefKind::Fn | DefKind::TyAlias => {
1612 if let DefKind::TyAlias = def_kind {
1613 self.check_unnameable(def_id, effective_vis);
1614 }
1615 self.check(def_id, item_visibility, effective_vis).generics().clauses().ty();
1616 }
1617 DefKind::OpaqueTy => {
1618 self.check(def_id, item_visibility, effective_vis).generics().bounds();
1621 }
1622 DefKind::Trait => {
1623 self.check_unnameable(def_id, effective_vis);
1624
1625 self.check(def_id, item_visibility, effective_vis).generics().clauses();
1626
1627 for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() {
1628 self.check_assoc_item(assoc_item, item_visibility, effective_vis);
1629 }
1630 }
1631 DefKind::TraitAlias => {
1632 self.check(def_id, item_visibility, effective_vis).generics().clauses();
1633 }
1634 DefKind::Enum => {
1635 self.check_unnameable(def_id, effective_vis);
1636 self.check(def_id, item_visibility, effective_vis).generics().clauses();
1637
1638 let adt = tcx.adt_def(id.owner_id);
1639 for field in adt.all_fields() {
1640 self.check(field.did.expect_local(), item_visibility, effective_vis).ty();
1641 }
1642 }
1643 DefKind::Struct | DefKind::Union => {
1645 self.check_unnameable(def_id, effective_vis);
1646 self.check(def_id, item_visibility, effective_vis).generics().clauses();
1647
1648 let adt = tcx.adt_def(id.owner_id);
1649 for field in adt.all_fields() {
1650 let visibility = min(item_visibility, field.vis.expect_local(), tcx);
1651 let field_ev = self.get(field.did.expect_local());
1652
1653 self.check(field.did.expect_local(), visibility, field_ev).ty();
1654 }
1655 }
1656 DefKind::ForeignMod => {}
1658 DefKind::Impl { of_trait } => {
1663 let impl_vis =
1664 ty::Visibility::of_impl::<false>(def_id, of_trait, tcx, &Default::default());
1665
1666 let impl_ev = EffectiveVisibility::of_impl::<false>(
1678 def_id,
1679 of_trait,
1680 tcx,
1681 self.effective_visibilities,
1682 );
1683
1684 let mut check = self.check(def_id, impl_vis, Some(impl_ev));
1685
1686 if !of_trait {
1689 check.generics().clauses();
1690 }
1691
1692 check.skip_assoc_tys = true;
1696 check.ty();
1697 if of_trait {
1698 check.trait_ref();
1699 }
1700
1701 for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() {
1702 let impl_item_vis = if !of_trait {
1703 min(tcx.local_visibility(assoc_item.def_id.expect_local()), impl_vis, tcx)
1704 } else {
1705 impl_vis
1706 };
1707
1708 let impl_item_ev = if !of_trait {
1709 self.get(assoc_item.def_id.expect_local())
1710 .map(|ev| ev.min(impl_ev, self.tcx))
1711 } else {
1712 Some(impl_ev)
1713 };
1714
1715 self.check_assoc_item(assoc_item, impl_item_vis, impl_item_ev);
1716 }
1717 }
1718 _ => {}
1719 }
1720 }
1721
1722 fn check_foreign_item(&self, id: ForeignItemId) {
1723 let tcx = self.tcx;
1724 let def_id = id.owner_id.def_id;
1725 let item_visibility = tcx.local_visibility(def_id);
1726 let effective_vis = self.get(def_id);
1727
1728 if let DefKind::ForeignTy = self.tcx.def_kind(def_id) {
1729 self.check_unnameable(def_id, effective_vis);
1730 }
1731
1732 self.check(def_id, item_visibility, effective_vis).generics().clauses().ty();
1733 }
1734}
1735
1736pub fn provide(providers: &mut Providers) {
1737 *providers = Providers {
1738 effective_visibilities,
1739 check_private_in_public,
1740 check_mod_privacy,
1741 ..*providers
1742 };
1743}
1744
1745fn check_mod_privacy(tcx: TyCtxt<'_>, mod_id: LocalModId) {
1746 let mut visitor = NamePrivacyVisitor { tcx, mod_id, maybe_typeck_results: None };
1748 tcx.hir_visit_item_likes_in_module(mod_id, &mut visitor);
1749
1750 let span = tcx.def_span(mod_id);
1753 let mut visitor = TypePrivacyVisitor {
1754 tcx,
1755 mod_id,
1756 maybe_typeck_results: None,
1757 span,
1758 accessible_tys: Default::default(),
1759 };
1760
1761 let module = tcx.hir_module_items(mod_id);
1762 for def_id in module.definitions() {
1763 let _ = rustc_ty_walk::walk_types(tcx, def_id, &mut visitor);
1764
1765 if let Some(body_id) = tcx.hir_maybe_body_owned_by(def_id) {
1766 visitor.visit_nested_body(body_id.id());
1767 }
1768
1769 if let DefKind::Impl { of_trait: true } = tcx.def_kind(def_id) {
1770 let trait_ref = tcx.impl_trait_ref(def_id);
1771 let trait_ref = trait_ref.instantiate_identity().skip_norm_wip();
1772 visitor.span =
1773 tcx.hir_expect_item(def_id).expect_impl().of_trait.unwrap().trait_ref.path.span;
1774 let _ =
1775 visitor.visit_def_id(trait_ref.def_id, "trait", &trait_ref.print_only_trait_path());
1776 }
1777 }
1778}
1779
1780fn effective_visibilities(tcx: TyCtxt<'_>, (): ()) -> &EffectiveVisibilities {
1781 let def_ids_to_impls = DefIdsToImplsCollector::collect(tcx);
1782
1783 let mut visitor = EmbargoVisitor {
1786 tcx,
1787 effective_visibilities: tcx.resolutions(()).effective_visibilities.clone(),
1788 queue: Default::default(),
1789 def_ids_to_impls,
1790 };
1791
1792 visitor.effective_visibilities.check_invariants(tcx);
1793
1794 let impl_trait_pass = !tcx.sess.opts.actually_rustdoc;
1798 if impl_trait_pass {
1799 let krate = tcx.hir_crate_items(());
1802 for id in krate.opaques() {
1803 let opaque = tcx.hir_node_by_def_id(id).expect_opaque_ty();
1804 let should_visit = match opaque.origin {
1805 hir::OpaqueTyOrigin::FnReturn {
1806 parent,
1807 in_trait_or_impl: Some(hir::RpitContext::Trait),
1808 }
1809 | hir::OpaqueTyOrigin::AsyncFn {
1810 parent,
1811 in_trait_or_impl: Some(hir::RpitContext::Trait),
1812 } => match tcx.hir_node_by_def_id(parent).expect_trait_item().expect_fn().1 {
1813 hir::TraitFn::Required(_) => false,
1814 hir::TraitFn::Provided(..) => true,
1815 },
1816
1817 hir::OpaqueTyOrigin::FnReturn {
1820 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
1821 ..
1822 }
1823 | hir::OpaqueTyOrigin::AsyncFn {
1824 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
1825 ..
1826 }
1827 | hir::OpaqueTyOrigin::TyAlias { .. } => true,
1828 };
1829 if should_visit {
1830 let pub_ev = EffectiveVisibility::from_vis(ty::Visibility::Public);
1834 visitor.reach_through_impl_trait(opaque.def_id, pub_ev).generics().clauses().ty();
1835 }
1836 }
1837
1838 visitor.queue.clear();
1839 }
1840
1841 for (&adt_def_id, macro_mods) in &tcx.resolutions(()).macro_reachable_adts {
1844 let struct_def = tcx.adt_def(adt_def_id);
1845 let Some(struct_ev) = visitor.effective_visibilities.effective_vis(adt_def_id).copied()
1846 else {
1847 continue;
1848 };
1849 for field in &struct_def.non_enum_variant().fields {
1850 let def_id = field.did.expect_local();
1851 let field_vis = tcx.local_visibility(def_id);
1852
1853 for ¯o_mod in macro_mods {
1854 if field_vis.is_accessible_from(macro_mod, tcx) {
1855 visitor.reach(def_id, struct_ev).ty();
1856 }
1857 }
1858 }
1859 }
1860
1861 let crate_items = tcx.hir_crate_items(());
1862 for id in crate_items.free_items() {
1863 visitor.check_def_id(id.owner_id.def_id);
1864 }
1865 for id in crate_items.foreign_items() {
1866 visitor.check_def_id(id.owner_id.def_id);
1867 }
1868 while let Some(def_id) = visitor.queue.pop() {
1869 visitor.check_def_id(def_id);
1870 }
1871 visitor.effective_visibilities.check_invariants(tcx);
1872
1873 let check_visitor =
1874 TestReachabilityVisitor { tcx, effective_visibilities: &visitor.effective_visibilities };
1875 for id in crate_items.owners() {
1876 check_visitor.check_def_id(id);
1877 }
1878
1879 tcx.arena.alloc(visitor.effective_visibilities)
1880}
1881
1882fn check_private_in_public(tcx: TyCtxt<'_>, mod_id: LocalModId) {
1883 let effective_visibilities = tcx.effective_visibilities(());
1884 let checker = PrivateItemsInPublicInterfacesChecker { tcx, effective_visibilities };
1886
1887 let crate_items = tcx.hir_module_items(mod_id);
1888 let _ = crate_items.par_items(|id| Ok(checker.check_item(id)));
1889 let _ = crate_items.par_foreign_items(|id| Ok(checker.check_foreign_item(id)));
1890}