1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
2 #![feature(associated_type_defaults)]
3 #![feature(control_flow_enum)]
4 #![feature(rustc_private)]
5 #![feature(try_blocks)]
6 #![recursion_limit = "256"]
7 #![deny(rustc::untranslatable_diagnostic)]
8 #![deny(rustc::diagnostic_outside_of_impl)]
15 use rustc_ast::MacroDef;
16 use rustc_attr as attr;
17 use rustc_data_structures::fx::FxHashSet;
18 use rustc_data_structures::intern::Interned;
20 use rustc_hir::def::{DefKind, Res};
21 use rustc_hir::def_id::{DefId, LocalDefId, LocalDefIdSet, CRATE_DEF_ID};
22 use rustc_hir::intravisit::{self, Visitor};
23 use rustc_hir::{AssocItemKind, HirIdSet, ItemId, Node, PatKind};
24 use rustc_middle::bug;
25 use rustc_middle::hir::nested_filter;
26 use rustc_middle::middle::privacy::{EffectiveVisibilities, Level};
27 use rustc_middle::span_bug;
28 use rustc_middle::ty::abstract_const::{walk_abstract_const, AbstractConst, Node as ACNode};
29 use rustc_middle::ty::query::Providers;
30 use rustc_middle::ty::subst::InternalSubsts;
31 use rustc_middle::ty::{self, Const, DefIdTree, GenericParamDefKind};
32 use rustc_middle::ty::{TraitRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor};
33 use rustc_session::lint;
34 use rustc_span::hygiene::Transparency;
35 use rustc_span::symbol::{kw, sym, Ident};
38 use std::marker::PhantomData;
39 use std::ops::ControlFlow;
40 use std::{cmp, fmt, mem};
43 FieldIsPrivate, FieldIsPrivateLabel, FromPrivateDependencyInPublicInterface, InPublicInterface,
44 InPublicInterfaceTraits, ItemIsPrivate, PrivateInPublicLint, ReportEffectiveVisibility,
48 ////////////////////////////////////////////////////////////////////////////////
49 /// Generic infrastructure used to implement specific visitors below.
50 ////////////////////////////////////////////////////////////////////////////////
52 /// Implemented to visit all `DefId`s in a type.
53 /// Visiting `DefId`s is useful because visibilities and reachabilities are attached to them.
54 /// The idea is to visit "all components of a type", as documented in
55 /// <https://github.com/rust-lang/rfcs/blob/master/text/2145-type-privacy.md#how-to-determine-visibility-of-a-type>.
56 /// The default type visitor (`TypeVisitor`) does most of the job, but it has some shortcomings.
57 /// First, it doesn't have overridable `fn visit_trait_ref`, so we have to catch trait `DefId`s
58 /// manually. Second, it doesn't visit some type components like signatures of fn types, or traits
59 /// in `impl Trait`, see individual comments in `DefIdVisitorSkeleton::visit_ty`.
60 trait DefIdVisitor<'tcx> {
63 fn tcx(&self) -> TyCtxt<'tcx>;
64 fn shallow(&self) -> bool {
67 fn skip_assoc_tys(&self) -> bool {
74 descr: &dyn fmt::Display,
75 ) -> ControlFlow<Self::BreakTy>;
77 /// Not overridden, but used to actually visit types and traits.
78 fn skeleton(&mut self) -> DefIdVisitorSkeleton<'_, 'tcx, Self> {
79 DefIdVisitorSkeleton {
81 visited_opaque_tys: Default::default(),
82 dummy: Default::default(),
85 fn visit(&mut self, ty_fragment: impl TypeVisitable<'tcx>) -> ControlFlow<Self::BreakTy> {
86 ty_fragment.visit_with(&mut self.skeleton())
88 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> ControlFlow<Self::BreakTy> {
89 self.skeleton().visit_trait(trait_ref)
91 fn visit_projection_ty(
93 projection: ty::ProjectionTy<'tcx>,
94 ) -> ControlFlow<Self::BreakTy> {
95 self.skeleton().visit_projection_ty(projection)
99 predicates: ty::GenericPredicates<'tcx>,
100 ) -> ControlFlow<Self::BreakTy> {
101 self.skeleton().visit_predicates(predicates)
105 struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> {
106 def_id_visitor: &'v mut V,
107 visited_opaque_tys: FxHashSet<DefId>,
108 dummy: PhantomData<TyCtxt<'tcx>>,
111 impl<'tcx, V> DefIdVisitorSkeleton<'_, 'tcx, V>
113 V: DefIdVisitor<'tcx> + ?Sized,
115 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> ControlFlow<V::BreakTy> {
116 let TraitRef { def_id, substs } = trait_ref;
117 self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref.print_only_trait_path())?;
118 if self.def_id_visitor.shallow() { ControlFlow::CONTINUE } else { substs.visit_with(self) }
121 fn visit_projection_ty(
123 projection: ty::ProjectionTy<'tcx>,
124 ) -> ControlFlow<V::BreakTy> {
125 let tcx = self.def_id_visitor.tcx();
126 let (trait_ref, assoc_substs) = if tcx.def_kind(projection.item_def_id)
127 != DefKind::ImplTraitPlaceholder
129 projection.trait_ref_and_own_substs(tcx)
131 // HACK(RPITIT): Remove this when RPITITs are lowered to regular assoc tys
132 let def_id = tcx.impl_trait_in_trait_parent(projection.item_def_id);
133 let trait_generics = tcx.generics_of(def_id);
135 ty::TraitRef { def_id, substs: projection.substs.truncate_to(tcx, trait_generics) },
136 &projection.substs[trait_generics.count()..],
139 self.visit_trait(trait_ref)?;
140 if self.def_id_visitor.shallow() {
141 ControlFlow::CONTINUE
143 assoc_substs.iter().try_for_each(|subst| subst.visit_with(self))
147 fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<V::BreakTy> {
148 match predicate.kind().skip_binder() {
149 ty::PredicateKind::Trait(ty::TraitPredicate {
153 }) => self.visit_trait(trait_ref),
154 ty::PredicateKind::Projection(ty::ProjectionPredicate { projection_ty, term }) => {
155 term.visit_with(self)?;
156 self.visit_projection_ty(projection_ty)
158 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _region)) => {
161 ty::PredicateKind::RegionOutlives(..) => ControlFlow::CONTINUE,
162 ty::PredicateKind::ConstEvaluatable(ct) => ct.visit_with(self),
163 ty::PredicateKind::WellFormed(arg) => arg.visit_with(self),
164 _ => bug!("unexpected predicate: {:?}", predicate),
170 predicates: ty::GenericPredicates<'tcx>,
171 ) -> ControlFlow<V::BreakTy> {
172 let ty::GenericPredicates { parent: _, predicates } = predicates;
173 predicates.iter().try_for_each(|&(predicate, _span)| self.visit_predicate(predicate))
177 impl<'tcx, V> TypeVisitor<'tcx> for DefIdVisitorSkeleton<'_, 'tcx, V>
179 V: DefIdVisitor<'tcx> + ?Sized,
181 type BreakTy = V::BreakTy;
183 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<V::BreakTy> {
184 let tcx = self.def_id_visitor.tcx();
185 // InternalSubsts are not visited here because they are visited below
186 // in `super_visit_with`.
188 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), ..)
189 | ty::Foreign(def_id)
190 | ty::FnDef(def_id, ..)
191 | ty::Closure(def_id, ..)
192 | ty::Generator(def_id, ..) => {
193 self.def_id_visitor.visit_def_id(def_id, "type", &ty)?;
194 if self.def_id_visitor.shallow() {
195 return ControlFlow::CONTINUE;
197 // Default type visitor doesn't visit signatures of fn types.
198 // Something like `fn() -> Priv {my_func}` is considered a private type even if
199 // `my_func` is public, so we need to visit signatures.
200 if let ty::FnDef(..) = ty.kind() {
201 tcx.fn_sig(def_id).visit_with(self)?;
203 // Inherent static methods don't have self type in substs.
204 // Something like `fn() {my_method}` type of the method
205 // `impl Pub<Priv> { pub fn my_method() {} }` is considered a private type,
206 // so we need to visit the self type additionally.
207 if let Some(assoc_item) = tcx.opt_associated_item(def_id) {
208 if let Some(impl_def_id) = assoc_item.impl_container(tcx) {
209 tcx.type_of(impl_def_id).visit_with(self)?;
213 ty::Projection(proj) => {
214 if self.def_id_visitor.skip_assoc_tys() {
215 // Visitors searching for minimal visibility/reachability want to
216 // conservatively approximate associated types like `<Type as Trait>::Alias`
217 // as visible/reachable even if both `Type` and `Trait` are private.
218 // Ideally, associated types should be substituted in the same way as
219 // free type aliases, but this isn't done yet.
220 return ControlFlow::CONTINUE;
222 // This will also visit substs if necessary, so we don't need to recurse.
223 return self.visit_projection_ty(proj);
225 ty::Dynamic(predicates, ..) => {
226 // All traits in the list are considered the "primary" part of the type
227 // and are visited by shallow visitors.
228 for predicate in predicates {
229 let trait_ref = match predicate.skip_binder() {
230 ty::ExistentialPredicate::Trait(trait_ref) => trait_ref,
231 ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx),
232 ty::ExistentialPredicate::AutoTrait(def_id) => {
233 ty::ExistentialTraitRef { def_id, substs: InternalSubsts::empty() }
236 let ty::ExistentialTraitRef { def_id, substs: _ } = trait_ref;
237 self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref)?;
240 ty::Opaque(def_id, ..) => {
241 // Skip repeated `Opaque`s to avoid infinite recursion.
242 if self.visited_opaque_tys.insert(def_id) {
243 // The intent is to treat `impl Trait1 + Trait2` identically to
244 // `dyn Trait1 + Trait2`. Therefore we ignore def-id of the opaque type itself
245 // (it either has no visibility, or its visibility is insignificant, like
246 // visibilities of type aliases) and recurse into bounds instead to go
247 // through the trait list (default type visitor doesn't visit those traits).
248 // All traits in the list are considered the "primary" part of the type
249 // and are visited by shallow visitors.
250 self.visit_predicates(ty::GenericPredicates {
252 predicates: tcx.explicit_item_bounds(def_id),
256 // These types don't have their own def-ids (but may have subcomponents
257 // with def-ids that should be visited recursively).
273 | ty::GeneratorWitness(..) => {}
274 ty::Bound(..) | ty::Placeholder(..) | ty::Infer(..) => {
275 bug!("unexpected type: {:?}", ty)
279 if self.def_id_visitor.shallow() {
280 ControlFlow::CONTINUE
282 ty.super_visit_with(self)
286 fn visit_const(&mut self, c: Const<'tcx>) -> ControlFlow<Self::BreakTy> {
287 self.visit_ty(c.ty())?;
288 let tcx = self.def_id_visitor.tcx();
289 if let Ok(Some(ct)) = AbstractConst::from_const(tcx, c) {
290 walk_abstract_const(tcx, ct, |node| match node.root(tcx) {
291 ACNode::Leaf(leaf) => self.visit_const(leaf),
292 ACNode::Cast(_, _, ty) => self.visit_ty(ty),
293 ACNode::Binop(..) | ACNode::UnaryOp(..) | ACNode::FunctionCall(_, _) => {
294 ControlFlow::CONTINUE
298 ControlFlow::CONTINUE
303 fn min(vis1: ty::Visibility, vis2: ty::Visibility, tcx: TyCtxt<'_>) -> ty::Visibility {
304 if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
307 ////////////////////////////////////////////////////////////////////////////////
308 /// Visitor used to determine impl visibility and reachability.
309 ////////////////////////////////////////////////////////////////////////////////
311 struct FindMin<'a, 'tcx, VL: VisibilityLike> {
313 effective_visibilities: &'a EffectiveVisibilities,
317 impl<'a, 'tcx, VL: VisibilityLike> DefIdVisitor<'tcx> for FindMin<'a, 'tcx, VL> {
318 fn tcx(&self) -> TyCtxt<'tcx> {
321 fn shallow(&self) -> bool {
324 fn skip_assoc_tys(&self) -> bool {
331 _descr: &dyn fmt::Display,
332 ) -> ControlFlow<Self::BreakTy> {
333 if let Some(def_id) = def_id.as_local() {
334 self.min = VL::new_min(self, def_id);
336 ControlFlow::CONTINUE
340 trait VisibilityLike: Sized {
342 const SHALLOW: bool = false;
343 fn new_min(find: &FindMin<'_, '_, Self>, def_id: LocalDefId) -> Self;
345 // Returns an over-approximation (`skip_assoc_tys` = true) of visibility due to
346 // associated types for which we can't determine visibility precisely.
350 effective_visibilities: &EffectiveVisibilities,
352 let mut find = FindMin { tcx, effective_visibilities, min: Self::MAX };
353 find.visit(tcx.type_of(def_id));
354 if let Some(trait_ref) = tcx.impl_trait_ref(def_id) {
355 find.visit_trait(trait_ref);
360 impl VisibilityLike for ty::Visibility {
361 const MAX: Self = ty::Visibility::Public;
362 fn new_min(find: &FindMin<'_, '_, Self>, def_id: LocalDefId) -> Self {
363 min(find.tcx.local_visibility(def_id), find.min, find.tcx)
366 impl VisibilityLike for Option<Level> {
367 const MAX: Self = Some(Level::Direct);
368 // Type inference is very smart sometimes.
369 // It can make an impl reachable even some components of its type or trait are unreachable.
370 // E.g. methods of `impl ReachableTrait<UnreachableTy> for ReachableTy<UnreachableTy> { ... }`
371 // can be usable from other crates (#57264). So we skip substs when calculating reachability
372 // and consider an impl reachable if its "shallow" type and trait are reachable.
374 // The assumption we make here is that type-inference won't let you use an impl without knowing
375 // both "shallow" version of its self type and "shallow" version of its trait if it exists
376 // (which require reaching the `DefId`s in them).
377 const SHALLOW: bool = true;
378 fn new_min(find: &FindMin<'_, '_, Self>, def_id: LocalDefId) -> Self {
379 cmp::min(find.effective_visibilities.public_at_level(def_id), find.min)
383 ////////////////////////////////////////////////////////////////////////////////
384 /// The embargo visitor, used to determine the exports of the AST.
385 ////////////////////////////////////////////////////////////////////////////////
387 struct EmbargoVisitor<'tcx> {
390 /// Effective visibilities for reachable nodes.
391 effective_visibilities: EffectiveVisibilities,
392 /// A set of pairs corresponding to modules, where the first module is
393 /// reachable via a macro that's defined in the second module. This cannot
394 /// be represented as reachable because it can't handle the following case:
396 /// pub mod n { // Should be `Public`
397 /// pub(crate) mod p { // Should *not* be accessible
398 /// pub fn f() -> i32 { 12 } // Must be `Reachable`
404 macro_reachable: FxHashSet<(LocalDefId, LocalDefId)>,
405 /// Previous visibility level; `None` means unreachable.
406 prev_level: Option<Level>,
407 /// Has something changed in the level map?
411 struct ReachEverythingInTheInterfaceVisitor<'a, 'tcx> {
412 level: Option<Level>,
413 item_def_id: LocalDefId,
414 ev: &'a mut EmbargoVisitor<'tcx>,
417 impl<'tcx> EmbargoVisitor<'tcx> {
418 fn get(&self, def_id: LocalDefId) -> Option<Level> {
419 self.effective_visibilities.public_at_level(def_id)
422 /// Updates node level and returns the updated level.
423 fn update(&mut self, def_id: LocalDefId, level: Option<Level>) -> Option<Level> {
424 let old_level = self.get(def_id);
425 // Visibility levels can only grow.
426 if level > old_level {
427 self.effective_visibilities.set_public_at_level(
429 || ty::Visibility::Restricted(self.tcx.parent_module_from_def_id(def_id)),
442 level: Option<Level>,
443 ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
444 ReachEverythingInTheInterfaceVisitor {
445 level: cmp::min(level, Some(Level::Reachable)),
451 // We have to make sure that the items that macros might reference
452 // are reachable, since they might be exported transitively.
453 fn update_reachability_from_macro(&mut self, local_def_id: LocalDefId, md: &MacroDef) {
454 // Non-opaque macros cannot make other items more accessible than they already are.
456 let hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
457 let attrs = self.tcx.hir().attrs(hir_id);
458 if attr::find_transparency(attrs, md.macro_rules).0 != Transparency::Opaque {
462 let macro_module_def_id = self.tcx.local_parent(local_def_id);
463 if self.tcx.opt_def_kind(macro_module_def_id) != Some(DefKind::Mod) {
464 // The macro's parent doesn't correspond to a `mod`, return early (#63164, #65252).
468 if self.get(local_def_id).is_none() {
472 // Since we are starting from an externally visible module,
473 // all the parents in the loop below are also guaranteed to be modules.
474 let mut module_def_id = macro_module_def_id;
476 let changed_reachability =
477 self.update_macro_reachable(module_def_id, macro_module_def_id);
478 if changed_reachability || module_def_id == CRATE_DEF_ID {
481 module_def_id = self.tcx.local_parent(module_def_id);
485 /// Updates the item as being reachable through a macro defined in the given
486 /// module. Returns `true` if the level has changed.
487 fn update_macro_reachable(
489 module_def_id: LocalDefId,
490 defining_mod: LocalDefId,
492 if self.macro_reachable.insert((module_def_id, defining_mod)) {
493 self.update_macro_reachable_mod(module_def_id, defining_mod);
500 fn update_macro_reachable_mod(&mut self, module_def_id: LocalDefId, defining_mod: LocalDefId) {
501 let module = self.tcx.hir().get_module(module_def_id).0;
502 for item_id in module.item_ids {
503 let def_kind = self.tcx.def_kind(item_id.owner_id);
504 let vis = self.tcx.local_visibility(item_id.owner_id.def_id);
505 self.update_macro_reachable_def(item_id.owner_id.def_id, def_kind, vis, defining_mod);
507 if let Some(exports) = self.tcx.module_reexports(module_def_id) {
508 for export in exports {
509 if export.vis.is_accessible_from(defining_mod, self.tcx) {
510 if let Res::Def(def_kind, def_id) = export.res {
511 if let Some(def_id) = def_id.as_local() {
512 let vis = self.tcx.local_visibility(def_id);
513 self.update_macro_reachable_def(def_id, def_kind, vis, defining_mod);
521 fn update_macro_reachable_def(
528 let level = Some(Level::Reachable);
530 self.update(def_id, level);
533 // No type privacy, so can be directly marked as reachable.
534 DefKind::Const | DefKind::Static(_) | DefKind::TraitAlias | DefKind::TyAlias => {
535 if vis.is_accessible_from(module, self.tcx) {
536 self.update(def_id, level);
540 // Hygiene isn't really implemented for `macro_rules!` macros at the
541 // moment. Accordingly, marking them as reachable is unwise. `macro` macros
542 // have normal hygiene, so we can treat them like other items without type
543 // privacy and mark them reachable.
544 DefKind::Macro(_) => {
545 let item = self.tcx.hir().expect_item(def_id);
546 if let hir::ItemKind::Macro(MacroDef { macro_rules: false, .. }, _) = item.kind {
547 if vis.is_accessible_from(module, self.tcx) {
548 self.update(def_id, level);
553 // We can't use a module name as the final segment of a path, except
554 // in use statements. Since re-export checking doesn't consider
555 // hygiene these don't need to be marked reachable. The contents of
556 // the module, however may be reachable.
558 if vis.is_accessible_from(module, self.tcx) {
559 self.update_macro_reachable(def_id, module);
563 DefKind::Struct | DefKind::Union => {
564 // While structs and unions have type privacy, their fields do not.
566 let item = self.tcx.hir().expect_item(def_id);
567 if let hir::ItemKind::Struct(ref struct_def, _)
568 | hir::ItemKind::Union(ref struct_def, _) = item.kind
570 for field in struct_def.fields() {
571 let field_vis = self.tcx.local_visibility(field.def_id);
572 if field_vis.is_accessible_from(module, self.tcx) {
573 self.reach(field.def_id, level).ty();
577 bug!("item {:?} with DefKind {:?}", item, def_kind);
582 // These have type privacy, so are not reachable unless they're
583 // public, or are not namespaced at all.
586 | DefKind::ConstParam
587 | DefKind::Ctor(_, _)
592 | DefKind::ImplTraitPlaceholder
597 | DefKind::LifetimeParam
598 | DefKind::ExternCrate
600 | DefKind::ForeignMod
602 | DefKind::InlineConst
607 | DefKind::Generator => (),
612 impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> {
613 type NestedFilter = nested_filter::All;
615 /// We want to visit items in the context of their containing
616 /// module and so forth, so supply a crate for doing a deep walk.
617 fn nested_visit_map(&mut self) -> Self::Map {
621 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
622 let item_level = match item.kind {
623 hir::ItemKind::Impl { .. } => {
624 let impl_level = Option::<Level>::of_impl(
625 item.owner_id.def_id,
627 &self.effective_visibilities,
629 self.update(item.owner_id.def_id, impl_level)
631 _ => self.get(item.owner_id.def_id),
634 // Update levels of nested things.
636 hir::ItemKind::Enum(ref def, _) => {
637 for variant in def.variants {
638 let variant_level = self.update(variant.def_id, item_level);
639 if let Some(ctor_def_id) = variant.data.ctor_def_id() {
640 self.update(ctor_def_id, item_level);
642 for field in variant.data.fields() {
643 self.update(field.def_id, variant_level);
647 hir::ItemKind::Impl(ref impl_) => {
648 for impl_item_ref in impl_.items {
649 if impl_.of_trait.is_some()
650 || self.tcx.visibility(impl_item_ref.id.owner_id).is_public()
652 self.update(impl_item_ref.id.owner_id.def_id, item_level);
656 hir::ItemKind::Trait(.., trait_item_refs) => {
657 for trait_item_ref in trait_item_refs {
658 self.update(trait_item_ref.id.owner_id.def_id, item_level);
661 hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => {
662 if let Some(ctor_def_id) = def.ctor_def_id() {
663 self.update(ctor_def_id, item_level);
665 for field in def.fields() {
666 let vis = self.tcx.visibility(field.def_id);
668 self.update(field.def_id, item_level);
672 hir::ItemKind::Macro(ref macro_def, _) => {
673 self.update_reachability_from_macro(item.owner_id.def_id, macro_def);
675 hir::ItemKind::ForeignMod { items, .. } => {
676 for foreign_item in items {
677 if self.tcx.visibility(foreign_item.id.owner_id).is_public() {
678 self.update(foreign_item.id.owner_id.def_id, item_level);
683 hir::ItemKind::OpaqueTy(..)
684 | hir::ItemKind::Use(..)
685 | hir::ItemKind::Static(..)
686 | hir::ItemKind::Const(..)
687 | hir::ItemKind::GlobalAsm(..)
688 | hir::ItemKind::TyAlias(..)
689 | hir::ItemKind::Mod(..)
690 | hir::ItemKind::TraitAlias(..)
691 | hir::ItemKind::Fn(..)
692 | hir::ItemKind::ExternCrate(..) => {}
695 // Mark all items in interfaces of reachable items as reachable.
697 // The interface is empty.
698 hir::ItemKind::Macro(..) | hir::ItemKind::ExternCrate(..) => {}
699 // All nested items are checked by `visit_item`.
700 hir::ItemKind::Mod(..) => {}
701 // Handled in `rustc_resolve`.
702 hir::ItemKind::Use(..) => {}
703 // The interface is empty.
704 hir::ItemKind::GlobalAsm(..) => {}
705 hir::ItemKind::OpaqueTy(ref opaque) => {
706 // HACK(jynelson): trying to infer the type of `impl trait` breaks `async-std` (and `pub async fn` in general)
707 // Since rustdoc never needs to do codegen and doesn't care about link-time reachability,
708 // mark this as unreachable.
709 // See https://github.com/rust-lang/rust/issues/75100
710 if !opaque.in_trait && !self.tcx.sess.opts.actually_rustdoc {
711 // FIXME: This is some serious pessimization intended to workaround deficiencies
712 // in the reachability pass (`middle/reachable.rs`). Types are marked as link-time
713 // reachable if they are returned via `impl Trait`, even from private functions.
714 let exist_level = cmp::max(item_level, Some(Level::ReachableThroughImplTrait));
715 self.reach(item.owner_id.def_id, exist_level).generics().predicates().ty();
719 hir::ItemKind::Const(..)
720 | hir::ItemKind::Static(..)
721 | hir::ItemKind::Fn(..)
722 | hir::ItemKind::TyAlias(..) => {
723 if item_level.is_some() {
724 self.reach(item.owner_id.def_id, item_level).generics().predicates().ty();
727 hir::ItemKind::Trait(.., trait_item_refs) => {
728 if item_level.is_some() {
729 self.reach(item.owner_id.def_id, item_level).generics().predicates();
731 for trait_item_ref in trait_item_refs {
733 let mut reach = self.reach(trait_item_ref.id.owner_id.def_id, item_level);
734 reach.generics().predicates();
736 if trait_item_ref.kind == AssocItemKind::Type
737 && !tcx.impl_defaultness(trait_item_ref.id.owner_id).has_value()
746 hir::ItemKind::TraitAlias(..) => {
747 if item_level.is_some() {
748 self.reach(item.owner_id.def_id, item_level).generics().predicates();
751 // Visit everything except for private impl items.
752 hir::ItemKind::Impl(ref impl_) => {
753 if item_level.is_some() {
754 self.reach(item.owner_id.def_id, item_level)
760 for impl_item_ref in impl_.items {
761 let impl_item_level = self.get(impl_item_ref.id.owner_id.def_id);
762 if impl_item_level.is_some() {
763 self.reach(impl_item_ref.id.owner_id.def_id, impl_item_level)
772 // Visit everything, but enum variants have their own levels.
773 hir::ItemKind::Enum(ref def, _) => {
774 if item_level.is_some() {
775 self.reach(item.owner_id.def_id, item_level).generics().predicates();
777 for variant in def.variants {
778 let variant_level = self.get(variant.def_id);
779 if variant_level.is_some() {
780 for field in variant.data.fields() {
781 self.reach(field.def_id, variant_level).ty();
783 // Corner case: if the variant is reachable, but its
784 // enum is not, make the enum reachable as well.
785 self.reach(item.owner_id.def_id, variant_level).ty();
787 if let Some(ctor_def_id) = variant.data.ctor_def_id() {
788 let ctor_level = self.get(ctor_def_id);
789 if ctor_level.is_some() {
790 self.reach(item.owner_id.def_id, ctor_level).ty();
795 // Visit everything, but foreign items have their own levels.
796 hir::ItemKind::ForeignMod { items, .. } => {
797 for foreign_item in items {
798 let foreign_item_level = self.get(foreign_item.id.owner_id.def_id);
799 if foreign_item_level.is_some() {
800 self.reach(foreign_item.id.owner_id.def_id, foreign_item_level)
807 // Visit everything except for private fields.
808 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
809 if item_level.is_some() {
810 self.reach(item.owner_id.def_id, item_level).generics().predicates();
811 for field in struct_def.fields() {
812 let field_level = self.get(field.def_id);
813 if field_level.is_some() {
814 self.reach(field.def_id, field_level).ty();
818 if let Some(ctor_def_id) = struct_def.ctor_def_id() {
819 let ctor_level = self.get(ctor_def_id);
820 if ctor_level.is_some() {
821 self.reach(item.owner_id.def_id, ctor_level).ty();
827 let orig_level = mem::replace(&mut self.prev_level, item_level);
828 intravisit::walk_item(self, item);
829 self.prev_level = orig_level;
832 fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
833 // Blocks can have public items, for example impls, but they always
834 // start as completely private regardless of publicity of a function,
835 // constant, type, field, etc., in which this block resides.
836 let orig_level = mem::replace(&mut self.prev_level, None);
837 intravisit::walk_block(self, b);
838 self.prev_level = orig_level;
842 impl ReachEverythingInTheInterfaceVisitor<'_, '_> {
843 fn generics(&mut self) -> &mut Self {
844 for param in &self.ev.tcx.generics_of(self.item_def_id).params {
846 GenericParamDefKind::Lifetime => {}
847 GenericParamDefKind::Type { has_default, .. } => {
849 self.visit(self.ev.tcx.type_of(param.def_id));
852 GenericParamDefKind::Const { has_default } => {
853 self.visit(self.ev.tcx.type_of(param.def_id));
855 self.visit(self.ev.tcx.const_param_default(param.def_id));
863 fn predicates(&mut self) -> &mut Self {
864 self.visit_predicates(self.ev.tcx.predicates_of(self.item_def_id));
868 fn ty(&mut self) -> &mut Self {
869 self.visit(self.ev.tcx.type_of(self.item_def_id));
873 fn trait_ref(&mut self) -> &mut Self {
874 if let Some(trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) {
875 self.visit_trait(trait_ref);
881 impl<'tcx> DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
882 fn tcx(&self) -> TyCtxt<'tcx> {
889 _descr: &dyn fmt::Display,
890 ) -> ControlFlow<Self::BreakTy> {
891 if let Some(def_id) = def_id.as_local() {
892 if let (ty::Visibility::Public, _) | (_, Some(Level::ReachableThroughImplTrait)) =
893 (self.tcx().visibility(def_id.to_def_id()), self.level)
895 self.ev.update(def_id, self.level);
898 ControlFlow::CONTINUE
902 ////////////////////////////////////////////////////////////////////////////////
903 /// Visitor, used for EffectiveVisibilities table checking
904 ////////////////////////////////////////////////////////////////////////////////
905 pub struct TestReachabilityVisitor<'tcx, 'a> {
907 effective_visibilities: &'a EffectiveVisibilities,
910 impl<'tcx, 'a> TestReachabilityVisitor<'tcx, 'a> {
911 fn effective_visibility_diagnostic(&mut self, def_id: LocalDefId) {
912 if self.tcx.has_attr(def_id.to_def_id(), sym::rustc_effective_visibility) {
913 let mut error_msg = String::new();
914 let span = self.tcx.def_span(def_id.to_def_id());
915 if let Some(effective_vis) = self.effective_visibilities.effective_vis(def_id) {
916 for level in Level::all_levels() {
917 let vis_str = match effective_vis.at_level(level) {
918 ty::Visibility::Restricted(restricted_id) => {
919 if restricted_id.is_top_level_module() {
920 "pub(crate)".to_string()
921 } else if *restricted_id == self.tcx.parent_module_from_def_id(def_id) {
922 "pub(self)".to_string()
924 format!("pub({})", self.tcx.item_name(restricted_id.to_def_id()))
927 ty::Visibility::Public => "pub".to_string(),
929 if level != Level::Direct {
930 error_msg.push_str(", ");
932 error_msg.push_str(&format!("{:?}: {}", level, vis_str));
935 error_msg.push_str("not in the table");
937 self.tcx.sess.emit_err(ReportEffectiveVisibility { span, descr: error_msg });
942 impl<'tcx, 'a> Visitor<'tcx> for TestReachabilityVisitor<'tcx, 'a> {
943 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
944 self.effective_visibility_diagnostic(item.owner_id.def_id);
947 hir::ItemKind::Enum(ref def, _) => {
948 for variant in def.variants.iter() {
949 self.effective_visibility_diagnostic(variant.def_id);
950 if let Some(ctor_def_id) = variant.data.ctor_def_id() {
951 self.effective_visibility_diagnostic(ctor_def_id);
953 for field in variant.data.fields() {
954 self.effective_visibility_diagnostic(field.def_id);
958 hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => {
959 if let Some(ctor_def_id) = def.ctor_def_id() {
960 self.effective_visibility_diagnostic(ctor_def_id);
962 for field in def.fields() {
963 self.effective_visibility_diagnostic(field.def_id);
970 fn visit_trait_item(&mut self, item: &'tcx hir::TraitItem<'tcx>) {
971 self.effective_visibility_diagnostic(item.owner_id.def_id);
973 fn visit_impl_item(&mut self, item: &'tcx hir::ImplItem<'tcx>) {
974 self.effective_visibility_diagnostic(item.owner_id.def_id);
976 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
977 self.effective_visibility_diagnostic(item.owner_id.def_id);
981 //////////////////////////////////////////////////////////////////////////////////////
982 /// Name privacy visitor, checks privacy and reports violations.
983 /// Most of name privacy checks are performed during the main resolution phase,
984 /// or later in type checking when field accesses and associated items are resolved.
985 /// This pass performs remaining checks for fields in struct expressions and patterns.
986 //////////////////////////////////////////////////////////////////////////////////////
988 struct NamePrivacyVisitor<'tcx> {
990 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
991 current_item: LocalDefId,
994 impl<'tcx> NamePrivacyVisitor<'tcx> {
995 /// Gets the type-checking results for the current body.
996 /// As this will ICE if called outside bodies, only call when working with
997 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
999 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
1000 self.maybe_typeck_results
1001 .expect("`NamePrivacyVisitor::typeck_results` called outside of body")
1004 // Checks that a field in a struct constructor (expression or pattern) is accessible.
1007 use_ctxt: Span, // syntax context of the field name at the use site
1008 span: Span, // span of the field pattern, e.g., `x: 0`
1009 def: ty::AdtDef<'tcx>, // definition of the struct or enum
1010 field: &'tcx ty::FieldDef,
1011 in_update_syntax: bool,
1017 // definition of the field
1018 let ident = Ident::new(kw::Empty, use_ctxt);
1019 let hir_id = self.tcx.hir().local_def_id_to_hir_id(self.current_item);
1020 let def_id = self.tcx.adjust_ident_and_get_scope(ident, def.did(), hir_id).1;
1021 if !field.vis.is_accessible_from(def_id, self.tcx) {
1022 self.tcx.sess.emit_err(FieldIsPrivate {
1024 field_name: field.name,
1025 variant_descr: def.variant_descr(),
1026 def_path_str: self.tcx.def_path_str(def.did()),
1027 label: if in_update_syntax {
1028 FieldIsPrivateLabel::IsUpdateSyntax { span, field_name: field.name }
1030 FieldIsPrivateLabel::Other { span }
1037 impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> {
1038 type NestedFilter = nested_filter::All;
1040 /// We want to visit items in the context of their containing
1041 /// module and so forth, so supply a crate for doing a deep walk.
1042 fn nested_visit_map(&mut self) -> Self::Map {
1046 fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) {
1047 // Don't visit nested modules, since we run a separate visitor walk
1048 // for each module in `effective_visibilities`
1051 fn visit_nested_body(&mut self, body: hir::BodyId) {
1052 let old_maybe_typeck_results =
1053 self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
1054 let body = self.tcx.hir().body(body);
1055 self.visit_body(body);
1056 self.maybe_typeck_results = old_maybe_typeck_results;
1059 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1060 let orig_current_item = mem::replace(&mut self.current_item, item.owner_id.def_id);
1061 intravisit::walk_item(self, item);
1062 self.current_item = orig_current_item;
1065 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1066 if let hir::ExprKind::Struct(qpath, fields, ref base) = expr.kind {
1067 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
1068 let adt = self.typeck_results().expr_ty(expr).ty_adt_def().unwrap();
1069 let variant = adt.variant_of_res(res);
1070 if let Some(base) = *base {
1071 // If the expression uses FRU we need to make sure all the unmentioned fields
1072 // are checked for privacy (RFC 736). Rather than computing the set of
1073 // unmentioned fields, just check them all.
1074 for (vf_index, variant_field) in variant.fields.iter().enumerate() {
1075 let field = fields.iter().find(|f| {
1076 self.tcx.field_index(f.hir_id, self.typeck_results()) == vf_index
1078 let (use_ctxt, span) = match field {
1079 Some(field) => (field.ident.span, field.span),
1080 None => (base.span, base.span),
1082 self.check_field(use_ctxt, span, adt, variant_field, true);
1085 for field in fields {
1086 let use_ctxt = field.ident.span;
1087 let index = self.tcx.field_index(field.hir_id, self.typeck_results());
1088 self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false);
1093 intravisit::walk_expr(self, expr);
1096 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
1097 if let PatKind::Struct(ref qpath, fields, _) = pat.kind {
1098 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
1099 let adt = self.typeck_results().pat_ty(pat).ty_adt_def().unwrap();
1100 let variant = adt.variant_of_res(res);
1101 for field in fields {
1102 let use_ctxt = field.ident.span;
1103 let index = self.tcx.field_index(field.hir_id, self.typeck_results());
1104 self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false);
1108 intravisit::walk_pat(self, pat);
1112 ////////////////////////////////////////////////////////////////////////////////////////////
1113 /// Type privacy visitor, checks types for privacy and reports violations.
1114 /// Both explicitly written types and inferred types of expressions and patterns are checked.
1115 /// Checks are performed on "semantic" types regardless of names and their hygiene.
1116 ////////////////////////////////////////////////////////////////////////////////////////////
1118 struct TypePrivacyVisitor<'tcx> {
1120 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
1121 current_item: LocalDefId,
1125 impl<'tcx> TypePrivacyVisitor<'tcx> {
1126 /// Gets the type-checking results for the current body.
1127 /// As this will ICE if called outside bodies, only call when working with
1128 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
1130 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
1131 self.maybe_typeck_results
1132 .expect("`TypePrivacyVisitor::typeck_results` called outside of body")
1135 fn item_is_accessible(&self, did: DefId) -> bool {
1136 self.tcx.visibility(did).is_accessible_from(self.current_item, self.tcx)
1139 // Take node-id of an expression or pattern and check its type for privacy.
1140 fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
1142 let typeck_results = self.typeck_results();
1143 let result: ControlFlow<()> = try {
1144 self.visit(typeck_results.node_type(id))?;
1145 self.visit(typeck_results.node_substs(id))?;
1146 if let Some(adjustments) = typeck_results.adjustments().get(id) {
1147 adjustments.iter().try_for_each(|adjustment| self.visit(adjustment.target))?;
1153 fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1154 let is_error = !self.item_is_accessible(def_id);
1156 self.tcx.sess.emit_err(ItemIsPrivate { span: self.span, kind, descr: descr.into() });
1162 impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> {
1163 type NestedFilter = nested_filter::All;
1165 /// We want to visit items in the context of their containing
1166 /// module and so forth, so supply a crate for doing a deep walk.
1167 fn nested_visit_map(&mut self) -> Self::Map {
1171 fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) {
1172 // Don't visit nested modules, since we run a separate visitor walk
1173 // for each module in `effective_visibilities`
1176 fn visit_nested_body(&mut self, body: hir::BodyId) {
1177 let old_maybe_typeck_results =
1178 self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
1179 let body = self.tcx.hir().body(body);
1180 self.visit_body(body);
1181 self.maybe_typeck_results = old_maybe_typeck_results;
1184 fn visit_generic_arg(&mut self, generic_arg: &'tcx hir::GenericArg<'tcx>) {
1186 hir::GenericArg::Type(t) => self.visit_ty(t),
1187 hir::GenericArg::Infer(inf) => self.visit_infer(inf),
1188 hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {}
1192 fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) {
1193 self.span = hir_ty.span;
1194 if let Some(typeck_results) = self.maybe_typeck_results {
1196 if self.visit(typeck_results.node_type(hir_ty.hir_id)).is_break() {
1200 // Types in signatures.
1201 // FIXME: This is very ineffective. Ideally each HIR type should be converted
1202 // into a semantic type only once and the result should be cached somehow.
1203 if self.visit(rustc_hir_analysis::hir_ty_to_ty(self.tcx, hir_ty)).is_break() {
1208 intravisit::walk_ty(self, hir_ty);
1211 fn visit_infer(&mut self, inf: &'tcx hir::InferArg) {
1212 self.span = inf.span;
1213 if let Some(typeck_results) = self.maybe_typeck_results {
1214 if let Some(ty) = typeck_results.node_type_opt(inf.hir_id) {
1215 if self.visit(ty).is_break() {
1219 // We don't do anything for const infers here.
1222 bug!("visit_infer without typeck_results");
1224 intravisit::walk_inf(self, inf);
1227 fn visit_trait_ref(&mut self, trait_ref: &'tcx hir::TraitRef<'tcx>) {
1228 self.span = trait_ref.path.span;
1229 if self.maybe_typeck_results.is_none() {
1230 // Avoid calling `hir_trait_to_predicates` in bodies, it will ICE.
1231 // The traits' privacy in bodies is already checked as a part of trait object types.
1232 let bounds = rustc_hir_analysis::hir_trait_to_predicates(
1235 // NOTE: This isn't really right, but the actual type doesn't matter here. It's
1236 // just required by `ty::TraitRef`.
1237 self.tcx.types.never,
1240 for (trait_predicate, _, _) in bounds.trait_bounds {
1241 if self.visit_trait(trait_predicate.skip_binder()).is_break() {
1246 for (poly_predicate, _) in bounds.projection_bounds {
1247 let pred = poly_predicate.skip_binder();
1248 let poly_pred_term = self.visit(pred.term);
1249 if poly_pred_term.is_break()
1250 || self.visit_projection_ty(pred.projection_ty).is_break()
1257 intravisit::walk_trait_ref(self, trait_ref);
1260 // Check types of expressions
1261 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1262 if self.check_expr_pat_type(expr.hir_id, expr.span) {
1263 // Do not check nested expressions if the error already happened.
1267 hir::ExprKind::Assign(_, rhs, _) | hir::ExprKind::Match(rhs, ..) => {
1268 // Do not report duplicate errors for `x = y` and `match x { ... }`.
1269 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
1273 hir::ExprKind::MethodCall(segment, ..) => {
1274 // Method calls have to be checked specially.
1275 self.span = segment.ident.span;
1276 if let Some(def_id) = self.typeck_results().type_dependent_def_id(expr.hir_id) {
1277 if self.visit(self.tcx.type_of(def_id)).is_break() {
1283 .delay_span_bug(expr.span, "no type-dependent def for method call");
1289 intravisit::walk_expr(self, expr);
1292 // Prohibit access to associated items with insufficient nominal visibility.
1294 // Additionally, until better reachability analysis for macros 2.0 is available,
1295 // we prohibit access to private statics from other crates, this allows to give
1296 // more code internal visibility at link time. (Access to private functions
1297 // is already prohibited by type privacy for function types.)
1298 fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) {
1299 let def = match qpath {
1300 hir::QPath::Resolved(_, path) => match path.res {
1301 Res::Def(kind, def_id) => Some((kind, def_id)),
1304 hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
1305 .maybe_typeck_results
1306 .and_then(|typeck_results| typeck_results.type_dependent_def(id)),
1308 let def = def.filter(|(kind, _)| {
1311 DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static(_)
1314 if let Some((kind, def_id)) = def {
1315 let is_local_static =
1316 if let DefKind::Static(_) = kind { def_id.is_local() } else { false };
1317 if !self.item_is_accessible(def_id) && !is_local_static {
1318 let sess = self.tcx.sess;
1319 let sm = sess.source_map();
1320 let name = match qpath {
1321 hir::QPath::Resolved(..) | hir::QPath::LangItem(..) => {
1322 sm.span_to_snippet(qpath.span()).ok()
1324 hir::QPath::TypeRelative(_, segment) => Some(segment.ident.to_string()),
1326 let kind = kind.descr(def_id);
1327 let _ = match name {
1329 sess.emit_err(ItemIsPrivate { span, kind, descr: (&name).into() })
1331 None => sess.emit_err(UnnamedItemIsPrivate { span, kind }),
1337 intravisit::walk_qpath(self, qpath, id);
1340 // Check types of patterns.
1341 fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) {
1342 if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
1343 // Do not check nested patterns if the error already happened.
1347 intravisit::walk_pat(self, pattern);
1350 fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) {
1351 if let Some(init) = local.init {
1352 if self.check_expr_pat_type(init.hir_id, init.span) {
1353 // Do not report duplicate errors for `let x = y`.
1358 intravisit::walk_local(self, local);
1361 // Check types in item interfaces.
1362 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1363 let orig_current_item = mem::replace(&mut self.current_item, item.owner_id.def_id);
1364 let old_maybe_typeck_results = self.maybe_typeck_results.take();
1365 intravisit::walk_item(self, item);
1366 self.maybe_typeck_results = old_maybe_typeck_results;
1367 self.current_item = orig_current_item;
1371 impl<'tcx> DefIdVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1372 fn tcx(&self) -> TyCtxt<'tcx> {
1379 descr: &dyn fmt::Display,
1380 ) -> ControlFlow<Self::BreakTy> {
1381 if self.check_def_id(def_id, kind, descr) {
1384 ControlFlow::CONTINUE
1389 ///////////////////////////////////////////////////////////////////////////////
1390 /// Obsolete visitors for checking for private items in public interfaces.
1391 /// These visitors are supposed to be kept in frozen state and produce an
1392 /// "old error node set". For backward compatibility the new visitor reports
1393 /// warnings instead of hard errors when the erroneous node is not in this old set.
1394 ///////////////////////////////////////////////////////////////////////////////
1396 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1398 effective_visibilities: &'a EffectiveVisibilities,
1400 // Set of errors produced by this obsolete visitor.
1401 old_error_set: HirIdSet,
1404 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1405 inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
1406 /// Whether the type refers to private types.
1407 contains_private: bool,
1408 /// Whether we've recurred at all (i.e., if we're pointing at the
1409 /// first type on which `visit_ty` was called).
1410 at_outer_type: bool,
1411 /// Whether that first type is a public path.
1412 outer_type_is_public_path: bool,
1415 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1416 fn path_is_private_type(&self, path: &hir::Path<'_>) -> bool {
1417 let did = match path.res {
1418 Res::PrimTy(..) | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } | Res::Err => {
1421 res => res.def_id(),
1424 // A path can only be private if:
1425 // it's in this crate...
1426 if let Some(did) = did.as_local() {
1427 // .. and it corresponds to a private type in the AST (this returns
1428 // `None` for type parameters).
1429 match self.tcx.hir().find(self.tcx.hir().local_def_id_to_hir_id(did)) {
1430 Some(Node::Item(_)) => !self.tcx.visibility(did).is_public(),
1431 Some(_) | None => false,
1438 fn trait_is_public(&self, trait_id: LocalDefId) -> bool {
1439 // FIXME: this would preferably be using `exported_items`, but all
1440 // traits are exported currently (see `EmbargoVisitor.exported_trait`).
1441 self.effective_visibilities.is_directly_public(trait_id)
1444 fn check_generic_bound(&mut self, bound: &hir::GenericBound<'_>) {
1445 if let hir::GenericBound::Trait(ref trait_ref, _) = *bound {
1446 if self.path_is_private_type(trait_ref.trait_ref.path) {
1447 self.old_error_set.insert(trait_ref.trait_ref.hir_ref_id);
1452 fn item_is_public(&self, def_id: LocalDefId) -> bool {
1453 self.effective_visibilities.is_reachable(def_id) || self.tcx.visibility(def_id).is_public()
1457 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1458 fn visit_generic_arg(&mut self, generic_arg: &'v hir::GenericArg<'v>) {
1460 hir::GenericArg::Type(t) => self.visit_ty(t),
1461 hir::GenericArg::Infer(inf) => self.visit_ty(&inf.to_ty()),
1462 hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {}
1466 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
1467 if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = ty.kind {
1468 if self.inner.path_is_private_type(path) {
1469 self.contains_private = true;
1470 // Found what we're looking for, so let's stop working.
1474 if let hir::TyKind::Path(_) = ty.kind {
1475 if self.at_outer_type {
1476 self.outer_type_is_public_path = true;
1479 self.at_outer_type = false;
1480 intravisit::walk_ty(self, ty)
1483 // Don't want to recurse into `[, .. expr]`.
1484 fn visit_expr(&mut self, _: &hir::Expr<'_>) {}
1487 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1488 type NestedFilter = nested_filter::All;
1490 /// We want to visit items in the context of their containing
1491 /// module and so forth, so supply a crate for doing a deep walk.
1492 fn nested_visit_map(&mut self) -> Self::Map {
1496 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1498 // Contents of a private mod can be re-exported, so we need
1499 // to check internals.
1500 hir::ItemKind::Mod(_) => {}
1502 // An `extern {}` doesn't introduce a new privacy
1503 // namespace (the contents have their own privacies).
1504 hir::ItemKind::ForeignMod { .. } => {}
1506 hir::ItemKind::Trait(.., bounds, _) => {
1507 if !self.trait_is_public(item.owner_id.def_id) {
1511 for bound in bounds.iter() {
1512 self.check_generic_bound(bound)
1516 // Impls need some special handling to try to offer useful
1517 // error messages without (too many) false positives
1518 // (i.e., we could just return here to not check them at
1519 // all, or some worse estimation of whether an impl is
1520 // publicly visible).
1521 hir::ItemKind::Impl(ref impl_) => {
1522 // `impl [... for] Private` is never visible.
1523 let self_contains_private;
1524 // `impl [... for] Public<...>`, but not `impl [... for]
1525 // Vec<Public>` or `(Public,)`, etc.
1526 let self_is_public_path;
1528 // Check the properties of the `Self` type:
1530 let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
1532 contains_private: false,
1533 at_outer_type: true,
1534 outer_type_is_public_path: false,
1536 visitor.visit_ty(impl_.self_ty);
1537 self_contains_private = visitor.contains_private;
1538 self_is_public_path = visitor.outer_type_is_public_path;
1541 // Miscellaneous info about the impl:
1543 // `true` iff this is `impl Private for ...`.
1544 let not_private_trait = impl_.of_trait.as_ref().map_or(
1545 true, // no trait counts as public trait
1547 if let Some(def_id) = tr.path.res.def_id().as_local() {
1548 self.trait_is_public(def_id)
1550 true // external traits must be public
1555 // `true` iff this is a trait impl or at least one method is public.
1557 // `impl Public { $( fn ...() {} )* }` is not visible.
1559 // This is required over just using the methods' privacy
1560 // directly because we might have `impl<T: Foo<Private>> ...`,
1561 // and we shouldn't warn about the generics if all the methods
1562 // are private (because `T` won't be visible externally).
1563 let trait_or_some_public_method = impl_.of_trait.is_some()
1564 || impl_.items.iter().any(|impl_item_ref| {
1565 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1566 match impl_item.kind {
1567 hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) => self
1568 .effective_visibilities
1569 .is_reachable(impl_item_ref.id.owner_id.def_id),
1570 hir::ImplItemKind::Type(_) => false,
1574 if !self_contains_private && not_private_trait && trait_or_some_public_method {
1575 intravisit::walk_generics(self, &impl_.generics);
1577 match impl_.of_trait {
1579 for impl_item_ref in impl_.items {
1580 // This is where we choose whether to walk down
1581 // further into the impl to check its items. We
1582 // should only walk into public items so that we
1583 // don't erroneously report errors for private
1584 // types in private items.
1585 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1586 match impl_item.kind {
1587 hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..)
1588 if self.item_is_public(impl_item.owner_id.def_id) =>
1590 intravisit::walk_impl_item(self, impl_item)
1592 hir::ImplItemKind::Type(..) => {
1593 intravisit::walk_impl_item(self, impl_item)
1600 // Any private types in a trait impl fall into three
1602 // 1. mentioned in the trait definition
1603 // 2. mentioned in the type params/generics
1604 // 3. mentioned in the associated types of the impl
1606 // Those in 1. can only occur if the trait is in
1607 // this crate and will have been warned about on the
1608 // trait definition (there's no need to warn twice
1609 // so we don't check the methods).
1611 // Those in 2. are warned via walk_generics and this
1613 intravisit::walk_path(self, tr.path);
1615 // Those in 3. are warned with this call.
1616 for impl_item_ref in impl_.items {
1617 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1618 if let hir::ImplItemKind::Type(ty) = impl_item.kind {
1624 } else if impl_.of_trait.is_none() && self_is_public_path {
1625 // `impl Public<Private> { ... }`. Any public static
1626 // methods will be visible as `Public::foo`.
1627 let mut found_pub_static = false;
1628 for impl_item_ref in impl_.items {
1630 .effective_visibilities
1631 .is_reachable(impl_item_ref.id.owner_id.def_id)
1632 || self.tcx.visibility(impl_item_ref.id.owner_id).is_public()
1634 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1635 match impl_item_ref.kind {
1636 AssocItemKind::Const => {
1637 found_pub_static = true;
1638 intravisit::walk_impl_item(self, impl_item);
1640 AssocItemKind::Fn { has_self: false } => {
1641 found_pub_static = true;
1642 intravisit::walk_impl_item(self, impl_item);
1648 if found_pub_static {
1649 intravisit::walk_generics(self, &impl_.generics)
1655 // `type ... = ...;` can contain private types, because
1656 // we're introducing a new name.
1657 hir::ItemKind::TyAlias(..) => return,
1659 // Not at all public, so we don't care.
1660 _ if !self.item_is_public(item.owner_id.def_id) => {
1667 // We've carefully constructed it so that if we're here, then
1668 // any `visit_ty`'s will be called on things that are in
1669 // public signatures, i.e., things that we're interested in for
1671 intravisit::walk_item(self, item);
1674 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1675 for predicate in generics.predicates {
1677 hir::WherePredicate::BoundPredicate(bound_pred) => {
1678 for bound in bound_pred.bounds.iter() {
1679 self.check_generic_bound(bound)
1682 hir::WherePredicate::RegionPredicate(_) => {}
1683 hir::WherePredicate::EqPredicate(eq_pred) => {
1684 self.visit_ty(eq_pred.rhs_ty);
1690 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
1691 if self.effective_visibilities.is_reachable(item.owner_id.def_id) {
1692 intravisit::walk_foreign_item(self, item)
1696 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
1697 if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = t.kind {
1698 if self.path_is_private_type(path) {
1699 self.old_error_set.insert(t.hir_id);
1702 intravisit::walk_ty(self, t)
1705 fn visit_variant(&mut self, v: &'tcx hir::Variant<'tcx>) {
1706 if self.effective_visibilities.is_reachable(v.def_id) {
1707 self.in_variant = true;
1708 intravisit::walk_variant(self, v);
1709 self.in_variant = false;
1713 fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) {
1714 let vis = self.tcx.visibility(s.def_id);
1715 if vis.is_public() || self.in_variant {
1716 intravisit::walk_field_def(self, s);
1720 // We don't need to introspect into these at all: an
1721 // expression/block context can't possibly contain exported things.
1722 // (Making them no-ops stops us from traversing the whole AST without
1723 // having to be super careful about our `walk_...` calls above.)
1724 fn visit_block(&mut self, _: &'tcx hir::Block<'tcx>) {}
1725 fn visit_expr(&mut self, _: &'tcx hir::Expr<'tcx>) {}
1728 ///////////////////////////////////////////////////////////////////////////////
1729 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1730 /// finds any private components in it.
1731 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1732 /// and traits in public interfaces.
1733 ///////////////////////////////////////////////////////////////////////////////
1735 struct SearchInterfaceForPrivateItemsVisitor<'tcx> {
1737 item_def_id: LocalDefId,
1738 /// The visitor checks that each component type is at least this visible.
1739 required_visibility: ty::Visibility,
1740 has_old_errors: bool,
1744 impl SearchInterfaceForPrivateItemsVisitor<'_> {
1745 fn generics(&mut self) -> &mut Self {
1746 for param in &self.tcx.generics_of(self.item_def_id).params {
1748 GenericParamDefKind::Lifetime => {}
1749 GenericParamDefKind::Type { has_default, .. } => {
1751 self.visit(self.tcx.type_of(param.def_id));
1754 // FIXME(generic_const_exprs): May want to look inside const here
1755 GenericParamDefKind::Const { .. } => {
1756 self.visit(self.tcx.type_of(param.def_id));
1763 fn predicates(&mut self) -> &mut Self {
1764 // N.B., we use `explicit_predicates_of` and not `predicates_of`
1765 // because we don't want to report privacy errors due to where
1766 // clauses that the compiler inferred. We only want to
1767 // consider the ones that the user wrote. This is important
1768 // for the inferred outlives rules; see
1769 // `src/test/ui/rfc-2093-infer-outlives/privacy.rs`.
1770 self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id));
1774 fn bounds(&mut self) -> &mut Self {
1775 self.visit_predicates(ty::GenericPredicates {
1777 predicates: self.tcx.explicit_item_bounds(self.item_def_id),
1782 fn ty(&mut self) -> &mut Self {
1783 self.visit(self.tcx.type_of(self.item_def_id));
1787 fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1788 if self.leaks_private_dep(def_id) {
1789 self.tcx.emit_spanned_lint(
1790 lint::builtin::EXPORTED_PRIVATE_DEPENDENCIES,
1791 self.tcx.hir().local_def_id_to_hir_id(self.item_def_id),
1792 self.tcx.def_span(self.item_def_id.to_def_id()),
1793 FromPrivateDependencyInPublicInterface {
1795 descr: descr.into(),
1796 krate: self.tcx.crate_name(def_id.krate),
1801 let Some(local_def_id) = def_id.as_local() else {
1805 let vis = self.tcx.local_visibility(local_def_id);
1806 if !vis.is_at_least(self.required_visibility, self.tcx) {
1807 let hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
1808 let vis_descr = match vis {
1809 ty::Visibility::Public => "public",
1810 ty::Visibility::Restricted(vis_def_id) => {
1811 if vis_def_id == self.tcx.parent_module(hir_id) {
1813 } else if vis_def_id.is_top_level_module() {
1820 let span = self.tcx.def_span(self.item_def_id.to_def_id());
1821 if self.has_old_errors
1823 || self.tcx.resolutions(()).has_pub_restricted
1825 let vis_span = self.tcx.def_span(def_id);
1826 if kind == "trait" {
1827 self.tcx.sess.emit_err(InPublicInterfaceTraits {
1831 descr: descr.into(),
1835 self.tcx.sess.emit_err(InPublicInterface {
1839 descr: descr.into(),
1844 self.tcx.emit_spanned_lint(
1845 lint::builtin::PRIVATE_IN_PUBLIC,
1848 PrivateInPublicLint { vis_descr, kind, descr: descr.into() },
1856 /// An item is 'leaked' from a private dependency if all
1857 /// of the following are true:
1858 /// 1. It's contained within a public type
1859 /// 2. It comes from a private crate
1860 fn leaks_private_dep(&self, item_id: DefId) -> bool {
1861 let ret = self.required_visibility.is_public() && self.tcx.is_private_dep(item_id.krate);
1863 debug!("leaks_private_dep(item_id={:?})={}", item_id, ret);
1868 impl<'tcx> DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> {
1869 fn tcx(&self) -> TyCtxt<'tcx> {
1876 descr: &dyn fmt::Display,
1877 ) -> ControlFlow<Self::BreakTy> {
1878 if self.check_def_id(def_id, kind, descr) {
1881 ControlFlow::CONTINUE
1886 struct PrivateItemsInPublicInterfacesChecker<'tcx> {
1888 old_error_set_ancestry: LocalDefIdSet,
1891 impl<'tcx> PrivateItemsInPublicInterfacesChecker<'tcx> {
1895 required_visibility: ty::Visibility,
1896 ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> {
1897 SearchInterfaceForPrivateItemsVisitor {
1899 item_def_id: def_id,
1900 required_visibility,
1901 has_old_errors: self.old_error_set_ancestry.contains(&def_id),
1906 fn check_assoc_item(
1909 assoc_item_kind: AssocItemKind,
1910 vis: ty::Visibility,
1912 let mut check = self.check(def_id, vis);
1914 let (check_ty, is_assoc_ty) = match assoc_item_kind {
1915 AssocItemKind::Const | AssocItemKind::Fn { .. } => (true, false),
1916 AssocItemKind::Type => (self.tcx.impl_defaultness(def_id).has_value(), true),
1918 check.in_assoc_ty = is_assoc_ty;
1919 check.generics().predicates();
1925 pub fn check_item(&mut self, id: ItemId) {
1927 let def_id = id.owner_id.def_id;
1928 let item_visibility = tcx.local_visibility(def_id);
1929 let def_kind = tcx.def_kind(def_id);
1932 DefKind::Const | DefKind::Static(_) | DefKind::Fn | DefKind::TyAlias => {
1933 self.check(def_id, item_visibility).generics().predicates().ty();
1935 DefKind::OpaqueTy => {
1936 // `ty()` for opaque types is the underlying type,
1937 // it's not a part of interface, so we skip it.
1938 self.check(def_id, item_visibility).generics().bounds();
1941 let item = tcx.hir().item(id);
1942 if let hir::ItemKind::Trait(.., trait_item_refs) = item.kind {
1943 self.check(item.owner_id.def_id, item_visibility).generics().predicates();
1945 for trait_item_ref in trait_item_refs {
1946 self.check_assoc_item(
1947 trait_item_ref.id.owner_id.def_id,
1948 trait_item_ref.kind,
1952 if let AssocItemKind::Type = trait_item_ref.kind {
1953 self.check(trait_item_ref.id.owner_id.def_id, item_visibility).bounds();
1958 DefKind::TraitAlias => {
1959 self.check(def_id, item_visibility).generics().predicates();
1962 let item = tcx.hir().item(id);
1963 if let hir::ItemKind::Enum(ref def, _) = item.kind {
1964 self.check(item.owner_id.def_id, item_visibility).generics().predicates();
1966 for variant in def.variants {
1967 for field in variant.data.fields() {
1968 self.check(field.def_id, item_visibility).ty();
1973 // Subitems of foreign modules have their own publicity.
1974 DefKind::ForeignMod => {
1975 let item = tcx.hir().item(id);
1976 if let hir::ItemKind::ForeignMod { items, .. } = item.kind {
1977 for foreign_item in items {
1978 let vis = tcx.local_visibility(foreign_item.id.owner_id.def_id);
1979 self.check(foreign_item.id.owner_id.def_id, vis)
1986 // Subitems of structs and unions have their own publicity.
1987 DefKind::Struct | DefKind::Union => {
1988 let item = tcx.hir().item(id);
1989 if let hir::ItemKind::Struct(ref struct_def, _)
1990 | hir::ItemKind::Union(ref struct_def, _) = item.kind
1992 self.check(item.owner_id.def_id, item_visibility).generics().predicates();
1994 for field in struct_def.fields() {
1995 let field_visibility = tcx.local_visibility(field.def_id);
1996 self.check(field.def_id, min(item_visibility, field_visibility, tcx)).ty();
2000 // An inherent impl is public when its type is public
2001 // Subitems of inherent impls have their own publicity.
2002 // A trait impl is public when both its type and its trait are public
2003 // Subitems of trait impls have inherited publicity.
2005 let item = tcx.hir().item(id);
2006 if let hir::ItemKind::Impl(ref impl_) = item.kind {
2008 ty::Visibility::of_impl(item.owner_id.def_id, tcx, &Default::default());
2009 // check that private components do not appear in the generics or predicates of inherent impls
2010 // this check is intentionally NOT performed for impls of traits, per #90586
2011 if impl_.of_trait.is_none() {
2012 self.check(item.owner_id.def_id, impl_vis).generics().predicates();
2014 for impl_item_ref in impl_.items {
2015 let impl_item_vis = if impl_.of_trait.is_none() {
2017 tcx.local_visibility(impl_item_ref.id.owner_id.def_id),
2024 self.check_assoc_item(
2025 impl_item_ref.id.owner_id.def_id,
2037 pub fn provide(providers: &mut Providers) {
2038 *providers = Providers {
2040 effective_visibilities,
2041 check_private_in_public,
2047 fn visibility(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Visibility<DefId> {
2048 local_visibility(tcx, def_id.expect_local()).to_def_id()
2051 fn local_visibility(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Visibility {
2052 match tcx.resolutions(()).visibilities.get(&def_id) {
2055 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2056 match tcx.hir().get(hir_id) {
2057 // Unique types created for closures participate in type privacy checking.
2058 // They have visibilities inherited from the module they are defined in.
2059 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure{..}, .. })
2060 // - AST lowering creates dummy `use` items which don't
2061 // get their entries in the resolver's visibility table.
2062 // - AST lowering also creates opaque type items with inherited visibilities.
2063 // Visibility on them should have no effect, but to avoid the visibility
2064 // query failing on some items, we provide it for opaque types as well.
2065 | Node::Item(hir::Item {
2066 kind: hir::ItemKind::Use(_, hir::UseKind::ListStem)
2067 | hir::ItemKind::OpaqueTy(..),
2069 }) => ty::Visibility::Restricted(tcx.parent_module(hir_id)),
2070 // Visibilities of trait impl items are inherited from their traits
2071 // and are not filled in resolve.
2072 Node::ImplItem(impl_item) => {
2073 match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(hir_id).def_id) {
2074 Node::Item(hir::Item {
2075 kind: hir::ItemKind::Impl(hir::Impl { of_trait: Some(tr), .. }),
2077 }) => tr.path.res.opt_def_id().map_or_else(
2079 tcx.sess.delay_span_bug(tr.path.span, "trait without a def-id");
2080 ty::Visibility::Public
2082 |def_id| tcx.visibility(def_id).expect_local(),
2084 _ => span_bug!(impl_item.span, "the parent is not a trait impl"),
2088 tcx.def_span(def_id),
2089 "visibility table unexpectedly missing a def-id: {:?}",
2097 fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
2098 // Check privacy of names not checked in previous compilation stages.
2100 NamePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id };
2101 let (module, span, hir_id) = tcx.hir().get_module(module_def_id);
2103 intravisit::walk_mod(&mut visitor, module, hir_id);
2105 // Check privacy of explicitly written types and traits as well as
2106 // inferred types of expressions and patterns.
2108 TypePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id, span };
2109 intravisit::walk_mod(&mut visitor, module, hir_id);
2112 fn effective_visibilities(tcx: TyCtxt<'_>, (): ()) -> &EffectiveVisibilities {
2113 // Build up a set of all exported items in the AST. This is a set of all
2114 // items which are reachable from external crates based on visibility.
2115 let mut visitor = EmbargoVisitor {
2117 effective_visibilities: tcx.resolutions(()).effective_visibilities.clone(),
2118 macro_reachable: Default::default(),
2119 prev_level: Some(Level::Direct),
2123 visitor.effective_visibilities.check_invariants(tcx, true);
2125 tcx.hir().walk_toplevel_module(&mut visitor);
2126 if visitor.changed {
2127 visitor.changed = false;
2132 visitor.effective_visibilities.check_invariants(tcx, false);
2134 let mut check_visitor =
2135 TestReachabilityVisitor { tcx, effective_visibilities: &visitor.effective_visibilities };
2136 tcx.hir().visit_all_item_likes_in_crate(&mut check_visitor);
2138 tcx.arena.alloc(visitor.effective_visibilities)
2141 fn check_private_in_public(tcx: TyCtxt<'_>, (): ()) {
2142 let effective_visibilities = tcx.effective_visibilities(());
2144 let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
2146 effective_visibilities,
2148 old_error_set: Default::default(),
2150 tcx.hir().walk_toplevel_module(&mut visitor);
2152 let mut old_error_set_ancestry = HirIdSet::default();
2153 for mut id in visitor.old_error_set.iter().copied() {
2155 if !old_error_set_ancestry.insert(id) {
2158 let parent = tcx.hir().get_parent_node(id);
2166 // Check for private types and traits in public interfaces.
2167 let mut checker = PrivateItemsInPublicInterfacesChecker {
2169 // Only definition IDs are ever searched in `old_error_set_ancestry`,
2170 // so we can filter away all non-definition IDs at this point.
2171 old_error_set_ancestry: old_error_set_ancestry
2173 .filter_map(|hir_id| tcx.hir().opt_local_def_id(hir_id))
2177 for id in tcx.hir().items() {
2178 checker.check_item(id);