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 #![allow(rustc::potential_query_instability)]
8 #![cfg_attr(not(bootstrap), deny(rustc::untranslatable_diagnostic))]
9 #![cfg_attr(not(bootstrap), deny(rustc::diagnostic_outside_of_impl))]
13 use rustc_ast::MacroDef;
14 use rustc_attr as attr;
15 use rustc_data_structures::fx::FxHashSet;
16 use rustc_data_structures::intern::Interned;
18 use rustc_hir::def::{DefKind, Res};
19 use rustc_hir::def_id::{DefId, LocalDefId, LocalDefIdSet, CRATE_DEF_ID};
20 use rustc_hir::intravisit::{self, Visitor};
21 use rustc_hir::{AssocItemKind, HirIdSet, ItemId, Node, PatKind};
22 use rustc_middle::bug;
23 use rustc_middle::hir::nested_filter;
24 use rustc_middle::middle::privacy::{AccessLevel, AccessLevels};
25 use rustc_middle::span_bug;
26 use rustc_middle::ty::abstract_const::{walk_abstract_const, AbstractConst, Node as ACNode};
27 use rustc_middle::ty::query::Providers;
28 use rustc_middle::ty::subst::InternalSubsts;
29 use rustc_middle::ty::{self, Const, DefIdTree, GenericParamDefKind};
30 use rustc_middle::ty::{TraitRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor};
31 use rustc_session::lint;
32 use rustc_span::hygiene::Transparency;
33 use rustc_span::symbol::{kw, Ident};
36 use std::marker::PhantomData;
37 use std::ops::ControlFlow;
38 use std::{cmp, fmt, mem};
41 FieldIsPrivate, FieldIsPrivateLabel, FromPrivateDependencyInPublicInterface, InPublicInterface,
42 InPublicInterfaceTraits, ItemIsPrivate, PrivateInPublicLint, UnnamedItemIsPrivate,
45 ////////////////////////////////////////////////////////////////////////////////
46 /// Generic infrastructure used to implement specific visitors below.
47 ////////////////////////////////////////////////////////////////////////////////
49 /// Implemented to visit all `DefId`s in a type.
50 /// Visiting `DefId`s is useful because visibilities and reachabilities are attached to them.
51 /// The idea is to visit "all components of a type", as documented in
52 /// <https://github.com/rust-lang/rfcs/blob/master/text/2145-type-privacy.md#how-to-determine-visibility-of-a-type>.
53 /// The default type visitor (`TypeVisitor`) does most of the job, but it has some shortcomings.
54 /// First, it doesn't have overridable `fn visit_trait_ref`, so we have to catch trait `DefId`s
55 /// manually. Second, it doesn't visit some type components like signatures of fn types, or traits
56 /// in `impl Trait`, see individual comments in `DefIdVisitorSkeleton::visit_ty`.
57 trait DefIdVisitor<'tcx> {
60 fn tcx(&self) -> TyCtxt<'tcx>;
61 fn shallow(&self) -> bool {
64 fn skip_assoc_tys(&self) -> bool {
71 descr: &dyn fmt::Display,
72 ) -> ControlFlow<Self::BreakTy>;
74 /// Not overridden, but used to actually visit types and traits.
75 fn skeleton(&mut self) -> DefIdVisitorSkeleton<'_, 'tcx, Self> {
76 DefIdVisitorSkeleton {
78 visited_opaque_tys: Default::default(),
79 dummy: Default::default(),
82 fn visit(&mut self, ty_fragment: impl TypeVisitable<'tcx>) -> ControlFlow<Self::BreakTy> {
83 ty_fragment.visit_with(&mut self.skeleton())
85 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> ControlFlow<Self::BreakTy> {
86 self.skeleton().visit_trait(trait_ref)
88 fn visit_projection_ty(
90 projection: ty::ProjectionTy<'tcx>,
91 ) -> ControlFlow<Self::BreakTy> {
92 self.skeleton().visit_projection_ty(projection)
96 predicates: ty::GenericPredicates<'tcx>,
97 ) -> ControlFlow<Self::BreakTy> {
98 self.skeleton().visit_predicates(predicates)
102 struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> {
103 def_id_visitor: &'v mut V,
104 visited_opaque_tys: FxHashSet<DefId>,
105 dummy: PhantomData<TyCtxt<'tcx>>,
108 impl<'tcx, V> DefIdVisitorSkeleton<'_, 'tcx, V>
110 V: DefIdVisitor<'tcx> + ?Sized,
112 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> ControlFlow<V::BreakTy> {
113 let TraitRef { def_id, substs } = trait_ref;
114 self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref.print_only_trait_path())?;
115 if self.def_id_visitor.shallow() { ControlFlow::CONTINUE } else { substs.visit_with(self) }
118 fn visit_projection_ty(
120 projection: ty::ProjectionTy<'tcx>,
121 ) -> ControlFlow<V::BreakTy> {
122 let (trait_ref, assoc_substs) =
123 projection.trait_ref_and_own_substs(self.def_id_visitor.tcx());
124 self.visit_trait(trait_ref)?;
125 if self.def_id_visitor.shallow() {
126 ControlFlow::CONTINUE
128 assoc_substs.iter().try_for_each(|subst| subst.visit_with(self))
132 fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<V::BreakTy> {
133 match predicate.kind().skip_binder() {
134 ty::PredicateKind::Trait(ty::TraitPredicate {
138 }) => self.visit_trait(trait_ref),
139 ty::PredicateKind::Projection(ty::ProjectionPredicate { projection_ty, term }) => {
140 term.visit_with(self)?;
141 self.visit_projection_ty(projection_ty)
143 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _region)) => {
146 ty::PredicateKind::RegionOutlives(..) => ControlFlow::CONTINUE,
147 ty::PredicateKind::ConstEvaluatable(uv)
148 if self.def_id_visitor.tcx().features().generic_const_exprs =>
150 let tcx = self.def_id_visitor.tcx();
151 if let Ok(Some(ct)) = AbstractConst::new(tcx, uv) {
152 self.visit_abstract_const_expr(tcx, ct)?;
154 ControlFlow::CONTINUE
156 ty::PredicateKind::WellFormed(arg) => arg.visit_with(self),
157 _ => bug!("unexpected predicate: {:?}", predicate),
161 fn visit_abstract_const_expr(
164 ct: AbstractConst<'tcx>,
165 ) -> ControlFlow<V::BreakTy> {
166 walk_abstract_const(tcx, ct, |node| match node.root(tcx) {
167 ACNode::Leaf(leaf) => self.visit_const(leaf),
168 ACNode::Cast(_, _, ty) => self.visit_ty(ty),
169 ACNode::Binop(..) | ACNode::UnaryOp(..) | ACNode::FunctionCall(_, _) => {
170 ControlFlow::CONTINUE
177 predicates: ty::GenericPredicates<'tcx>,
178 ) -> ControlFlow<V::BreakTy> {
179 let ty::GenericPredicates { parent: _, predicates } = predicates;
180 predicates.iter().try_for_each(|&(predicate, _span)| self.visit_predicate(predicate))
184 impl<'tcx, V> TypeVisitor<'tcx> for DefIdVisitorSkeleton<'_, 'tcx, V>
186 V: DefIdVisitor<'tcx> + ?Sized,
188 type BreakTy = V::BreakTy;
190 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<V::BreakTy> {
191 let tcx = self.def_id_visitor.tcx();
192 // InternalSubsts are not visited here because they are visited below
193 // in `super_visit_with`.
195 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), ..)
196 | ty::Foreign(def_id)
197 | ty::FnDef(def_id, ..)
198 | ty::Closure(def_id, ..)
199 | ty::Generator(def_id, ..) => {
200 self.def_id_visitor.visit_def_id(def_id, "type", &ty)?;
201 if self.def_id_visitor.shallow() {
202 return ControlFlow::CONTINUE;
204 // Default type visitor doesn't visit signatures of fn types.
205 // Something like `fn() -> Priv {my_func}` is considered a private type even if
206 // `my_func` is public, so we need to visit signatures.
207 if let ty::FnDef(..) = ty.kind() {
208 tcx.fn_sig(def_id).visit_with(self)?;
210 // Inherent static methods don't have self type in substs.
211 // Something like `fn() {my_method}` type of the method
212 // `impl Pub<Priv> { pub fn my_method() {} }` is considered a private type,
213 // so we need to visit the self type additionally.
214 if let Some(assoc_item) = tcx.opt_associated_item(def_id) {
215 if let Some(impl_def_id) = assoc_item.impl_container(tcx) {
216 tcx.type_of(impl_def_id).visit_with(self)?;
220 ty::Projection(proj) => {
221 if self.def_id_visitor.skip_assoc_tys() {
222 // Visitors searching for minimal visibility/reachability want to
223 // conservatively approximate associated types like `<Type as Trait>::Alias`
224 // as visible/reachable even if both `Type` and `Trait` are private.
225 // Ideally, associated types should be substituted in the same way as
226 // free type aliases, but this isn't done yet.
227 return ControlFlow::CONTINUE;
229 // This will also visit substs if necessary, so we don't need to recurse.
230 return self.visit_projection_ty(proj);
232 ty::Dynamic(predicates, ..) => {
233 // All traits in the list are considered the "primary" part of the type
234 // and are visited by shallow visitors.
235 for predicate in predicates {
236 let trait_ref = match predicate.skip_binder() {
237 ty::ExistentialPredicate::Trait(trait_ref) => trait_ref,
238 ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx),
239 ty::ExistentialPredicate::AutoTrait(def_id) => {
240 ty::ExistentialTraitRef { def_id, substs: InternalSubsts::empty() }
243 let ty::ExistentialTraitRef { def_id, substs: _ } = trait_ref;
244 self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref)?;
247 ty::Opaque(def_id, ..) => {
248 // Skip repeated `Opaque`s to avoid infinite recursion.
249 if self.visited_opaque_tys.insert(def_id) {
250 // The intent is to treat `impl Trait1 + Trait2` identically to
251 // `dyn Trait1 + Trait2`. Therefore we ignore def-id of the opaque type itself
252 // (it either has no visibility, or its visibility is insignificant, like
253 // visibilities of type aliases) and recurse into bounds instead to go
254 // through the trait list (default type visitor doesn't visit those traits).
255 // All traits in the list are considered the "primary" part of the type
256 // and are visited by shallow visitors.
257 self.visit_predicates(ty::GenericPredicates {
259 predicates: tcx.explicit_item_bounds(def_id),
263 // These types don't have their own def-ids (but may have subcomponents
264 // with def-ids that should be visited recursively).
280 | ty::GeneratorWitness(..) => {}
281 ty::Bound(..) | ty::Placeholder(..) | ty::Infer(..) => {
282 bug!("unexpected type: {:?}", ty)
286 if self.def_id_visitor.shallow() {
287 ControlFlow::CONTINUE
289 ty.super_visit_with(self)
293 fn visit_const(&mut self, c: Const<'tcx>) -> ControlFlow<Self::BreakTy> {
294 self.visit_ty(c.ty())?;
295 let tcx = self.def_id_visitor.tcx();
296 if let Ok(Some(ct)) = AbstractConst::from_const(tcx, c) {
297 self.visit_abstract_const_expr(tcx, ct)?;
299 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 access_levels: &'a AccessLevels,
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 self.min = VL::new_min(self, def_id);
334 ControlFlow::CONTINUE
338 trait VisibilityLike: Sized {
340 const SHALLOW: bool = false;
341 fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self;
343 // Returns an over-approximation (`skip_assoc_tys` = true) of visibility due to
344 // associated types for which we can't determine visibility precisely.
345 fn of_impl(def_id: LocalDefId, tcx: TyCtxt<'_>, access_levels: &AccessLevels) -> Self {
346 let mut find = FindMin { tcx, access_levels, min: Self::MAX };
347 find.visit(tcx.type_of(def_id));
348 if let Some(trait_ref) = tcx.impl_trait_ref(def_id) {
349 find.visit_trait(trait_ref);
354 impl VisibilityLike for ty::Visibility {
355 const MAX: Self = ty::Visibility::Public;
356 fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self {
357 min(find.tcx.visibility(def_id), find.min, find.tcx)
360 impl VisibilityLike for Option<AccessLevel> {
361 const MAX: Self = Some(AccessLevel::Public);
362 // Type inference is very smart sometimes.
363 // It can make an impl reachable even some components of its type or trait are unreachable.
364 // E.g. methods of `impl ReachableTrait<UnreachableTy> for ReachableTy<UnreachableTy> { ... }`
365 // can be usable from other crates (#57264). So we skip substs when calculating reachability
366 // and consider an impl reachable if its "shallow" type and trait are reachable.
368 // The assumption we make here is that type-inference won't let you use an impl without knowing
369 // both "shallow" version of its self type and "shallow" version of its trait if it exists
370 // (which require reaching the `DefId`s in them).
371 const SHALLOW: bool = true;
372 fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self {
374 if let Some(def_id) = def_id.as_local() {
375 find.access_levels.map.get(&def_id).copied()
384 ////////////////////////////////////////////////////////////////////////////////
385 /// The embargo visitor, used to determine the exports of the AST.
386 ////////////////////////////////////////////////////////////////////////////////
388 struct EmbargoVisitor<'tcx> {
391 /// Accessibility levels for reachable nodes.
392 access_levels: AccessLevels,
393 /// A set of pairs corresponding to modules, where the first module is
394 /// reachable via a macro that's defined in the second module. This cannot
395 /// be represented as reachable because it can't handle the following case:
397 /// pub mod n { // Should be `Public`
398 /// pub(crate) mod p { // Should *not* be accessible
399 /// pub fn f() -> i32 { 12 } // Must be `Reachable`
405 macro_reachable: FxHashSet<(LocalDefId, LocalDefId)>,
406 /// Previous accessibility level; `None` means unreachable.
407 prev_level: Option<AccessLevel>,
408 /// Has something changed in the level map?
412 struct ReachEverythingInTheInterfaceVisitor<'a, 'tcx> {
413 access_level: Option<AccessLevel>,
414 item_def_id: LocalDefId,
415 ev: &'a mut EmbargoVisitor<'tcx>,
418 impl<'tcx> EmbargoVisitor<'tcx> {
419 fn get(&self, def_id: LocalDefId) -> Option<AccessLevel> {
420 self.access_levels.map.get(&def_id).copied()
423 fn update_with_hir_id(
426 level: Option<AccessLevel>,
427 ) -> Option<AccessLevel> {
428 let def_id = self.tcx.hir().local_def_id(hir_id);
429 self.update(def_id, level)
432 /// Updates node level and returns the updated level.
433 fn update(&mut self, def_id: LocalDefId, level: Option<AccessLevel>) -> Option<AccessLevel> {
434 let old_level = self.get(def_id);
435 // Accessibility levels can only grow.
436 if level > old_level {
437 self.access_levels.map.insert(def_id, level.unwrap());
448 access_level: Option<AccessLevel>,
449 ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
450 ReachEverythingInTheInterfaceVisitor {
451 access_level: cmp::min(access_level, Some(AccessLevel::Reachable)),
457 // We have to make sure that the items that macros might reference
458 // are reachable, since they might be exported transitively.
459 fn update_reachability_from_macro(&mut self, local_def_id: LocalDefId, md: &MacroDef) {
460 // Non-opaque macros cannot make other items more accessible than they already are.
462 let hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
463 let attrs = self.tcx.hir().attrs(hir_id);
464 if attr::find_transparency(attrs, md.macro_rules).0 != Transparency::Opaque {
468 let macro_module_def_id = self.tcx.local_parent(local_def_id);
469 if self.tcx.opt_def_kind(macro_module_def_id) != Some(DefKind::Mod) {
470 // The macro's parent doesn't correspond to a `mod`, return early (#63164, #65252).
474 if self.get(local_def_id).is_none() {
478 // Since we are starting from an externally visible module,
479 // all the parents in the loop below are also guaranteed to be modules.
480 let mut module_def_id = macro_module_def_id;
482 let changed_reachability =
483 self.update_macro_reachable(module_def_id, macro_module_def_id);
484 if changed_reachability || module_def_id == CRATE_DEF_ID {
487 module_def_id = self.tcx.local_parent(module_def_id);
491 /// Updates the item as being reachable through a macro defined in the given
492 /// module. Returns `true` if the level has changed.
493 fn update_macro_reachable(
495 module_def_id: LocalDefId,
496 defining_mod: LocalDefId,
498 if self.macro_reachable.insert((module_def_id, defining_mod)) {
499 self.update_macro_reachable_mod(module_def_id, defining_mod);
506 fn update_macro_reachable_mod(&mut self, module_def_id: LocalDefId, defining_mod: LocalDefId) {
507 let module = self.tcx.hir().get_module(module_def_id).0;
508 for item_id in module.item_ids {
509 let def_kind = self.tcx.def_kind(item_id.def_id);
510 let vis = self.tcx.visibility(item_id.def_id);
511 self.update_macro_reachable_def(item_id.def_id, def_kind, vis, defining_mod);
513 if let Some(exports) = self.tcx.module_reexports(module_def_id) {
514 for export in exports {
515 if export.vis.is_accessible_from(defining_mod.to_def_id(), self.tcx) {
516 if let Res::Def(def_kind, def_id) = export.res {
517 if let Some(def_id) = def_id.as_local() {
518 let vis = self.tcx.visibility(def_id.to_def_id());
519 self.update_macro_reachable_def(def_id, def_kind, vis, defining_mod);
527 fn update_macro_reachable_def(
534 let level = Some(AccessLevel::Reachable);
536 self.update(def_id, level);
539 // No type privacy, so can be directly marked as reachable.
540 DefKind::Const | DefKind::Static(_) | DefKind::TraitAlias | DefKind::TyAlias => {
541 if vis.is_accessible_from(module.to_def_id(), self.tcx) {
542 self.update(def_id, level);
546 // Hygiene isn't really implemented for `macro_rules!` macros at the
547 // moment. Accordingly, marking them as reachable is unwise. `macro` macros
548 // have normal hygiene, so we can treat them like other items without type
549 // privacy and mark them reachable.
550 DefKind::Macro(_) => {
551 let item = self.tcx.hir().expect_item(def_id);
552 if let hir::ItemKind::Macro(MacroDef { macro_rules: false, .. }, _) = item.kind {
553 if vis.is_accessible_from(module.to_def_id(), self.tcx) {
554 self.update(def_id, level);
559 // We can't use a module name as the final segment of a path, except
560 // in use statements. Since re-export checking doesn't consider
561 // hygiene these don't need to be marked reachable. The contents of
562 // the module, however may be reachable.
564 if vis.is_accessible_from(module.to_def_id(), self.tcx) {
565 self.update_macro_reachable(def_id, module);
569 DefKind::Struct | DefKind::Union => {
570 // While structs and unions have type privacy, their fields do not.
572 let item = self.tcx.hir().expect_item(def_id);
573 if let hir::ItemKind::Struct(ref struct_def, _)
574 | hir::ItemKind::Union(ref struct_def, _) = item.kind
576 for field in struct_def.fields() {
577 let def_id = self.tcx.hir().local_def_id(field.hir_id);
578 let field_vis = self.tcx.visibility(def_id);
579 if field_vis.is_accessible_from(module.to_def_id(), self.tcx) {
580 self.reach(def_id, level).ty();
584 bug!("item {:?} with DefKind {:?}", item, def_kind);
589 // These have type privacy, so are not reachable unless they're
590 // public, or are not namespaced at all.
593 | DefKind::ConstParam
594 | DefKind::Ctor(_, _)
603 | DefKind::LifetimeParam
604 | DefKind::ExternCrate
606 | DefKind::ForeignMod
608 | DefKind::InlineConst
613 | DefKind::Generator => (),
618 impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> {
619 type NestedFilter = nested_filter::All;
621 /// We want to visit items in the context of their containing
622 /// module and so forth, so supply a crate for doing a deep walk.
623 fn nested_visit_map(&mut self) -> Self::Map {
627 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
628 let item_level = match item.kind {
629 hir::ItemKind::Impl { .. } => {
631 Option::<AccessLevel>::of_impl(item.def_id, self.tcx, &self.access_levels);
632 self.update(item.def_id, impl_level)
634 _ => self.get(item.def_id),
637 // Update levels of nested things.
639 hir::ItemKind::Enum(ref def, _) => {
640 for variant in def.variants {
641 let variant_level = self.update_with_hir_id(variant.id, item_level);
642 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
643 self.update_with_hir_id(ctor_hir_id, item_level);
645 for field in variant.data.fields() {
646 self.update_with_hir_id(field.hir_id, variant_level);
650 hir::ItemKind::Impl(ref impl_) => {
651 for impl_item_ref in impl_.items {
652 if impl_.of_trait.is_some()
653 || self.tcx.visibility(impl_item_ref.id.def_id) == ty::Visibility::Public
655 self.update(impl_item_ref.id.def_id, item_level);
659 hir::ItemKind::Trait(.., trait_item_refs) => {
660 for trait_item_ref in trait_item_refs {
661 self.update(trait_item_ref.id.def_id, item_level);
664 hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => {
665 if let Some(ctor_hir_id) = def.ctor_hir_id() {
666 self.update_with_hir_id(ctor_hir_id, item_level);
668 for field in def.fields() {
669 let def_id = self.tcx.hir().local_def_id(field.hir_id);
670 let vis = self.tcx.visibility(def_id);
672 self.update_with_hir_id(field.hir_id, item_level);
676 hir::ItemKind::Macro(ref macro_def, _) => {
677 self.update_reachability_from_macro(item.def_id, macro_def);
679 hir::ItemKind::ForeignMod { items, .. } => {
680 for foreign_item in items {
681 if self.tcx.visibility(foreign_item.id.def_id) == ty::Visibility::Public {
682 self.update(foreign_item.id.def_id, item_level);
687 hir::ItemKind::OpaqueTy(..)
688 | hir::ItemKind::Use(..)
689 | hir::ItemKind::Static(..)
690 | hir::ItemKind::Const(..)
691 | hir::ItemKind::GlobalAsm(..)
692 | hir::ItemKind::TyAlias(..)
693 | hir::ItemKind::Mod(..)
694 | hir::ItemKind::TraitAlias(..)
695 | hir::ItemKind::Fn(..)
696 | hir::ItemKind::ExternCrate(..) => {}
699 // Mark all items in interfaces of reachable items as reachable.
701 // The interface is empty.
702 hir::ItemKind::Macro(..) | hir::ItemKind::ExternCrate(..) => {}
703 // All nested items are checked by `visit_item`.
704 hir::ItemKind::Mod(..) => {}
705 // Handled in the access level of in rustc_resolve
706 hir::ItemKind::Use(..) => {}
707 // The interface is empty.
708 hir::ItemKind::GlobalAsm(..) => {}
709 hir::ItemKind::OpaqueTy(..) => {
710 // HACK(jynelson): trying to infer the type of `impl trait` breaks `async-std` (and `pub async fn` in general)
711 // Since rustdoc never needs to do codegen and doesn't care about link-time reachability,
712 // mark this as unreachable.
713 // See https://github.com/rust-lang/rust/issues/75100
714 if !self.tcx.sess.opts.actually_rustdoc {
715 // FIXME: This is some serious pessimization intended to workaround deficiencies
716 // in the reachability pass (`middle/reachable.rs`). Types are marked as link-time
717 // reachable if they are returned via `impl Trait`, even from private functions.
719 cmp::max(item_level, Some(AccessLevel::ReachableFromImplTrait));
720 self.reach(item.def_id, exist_level).generics().predicates().ty();
724 hir::ItemKind::Const(..)
725 | hir::ItemKind::Static(..)
726 | hir::ItemKind::Fn(..)
727 | hir::ItemKind::TyAlias(..) => {
728 if item_level.is_some() {
729 self.reach(item.def_id, item_level).generics().predicates().ty();
732 hir::ItemKind::Trait(.., trait_item_refs) => {
733 if item_level.is_some() {
734 self.reach(item.def_id, item_level).generics().predicates();
736 for trait_item_ref in trait_item_refs {
738 let mut reach = self.reach(trait_item_ref.id.def_id, item_level);
739 reach.generics().predicates();
741 if trait_item_ref.kind == AssocItemKind::Type
742 && !tcx.impl_defaultness(trait_item_ref.id.def_id).has_value()
751 hir::ItemKind::TraitAlias(..) => {
752 if item_level.is_some() {
753 self.reach(item.def_id, item_level).generics().predicates();
756 // Visit everything except for private impl items.
757 hir::ItemKind::Impl(ref impl_) => {
758 if item_level.is_some() {
759 self.reach(item.def_id, item_level).generics().predicates().ty().trait_ref();
761 for impl_item_ref in impl_.items {
762 let impl_item_level = self.get(impl_item_ref.id.def_id);
763 if impl_item_level.is_some() {
764 self.reach(impl_item_ref.id.def_id, impl_item_level)
773 // Visit everything, but enum variants have their own levels.
774 hir::ItemKind::Enum(ref def, _) => {
775 if item_level.is_some() {
776 self.reach(item.def_id, item_level).generics().predicates();
778 for variant in def.variants {
779 let variant_level = self.get(self.tcx.hir().local_def_id(variant.id));
780 if variant_level.is_some() {
781 for field in variant.data.fields() {
782 self.reach(self.tcx.hir().local_def_id(field.hir_id), variant_level)
785 // Corner case: if the variant is reachable, but its
786 // enum is not, make the enum reachable as well.
787 self.reach(item.def_id, variant_level).ty();
789 if let Some(hir_id) = variant.data.ctor_hir_id() {
790 let ctor_def_id = self.tcx.hir().local_def_id(hir_id);
791 let ctor_level = self.get(ctor_def_id);
792 if ctor_level.is_some() {
793 self.reach(item.def_id, ctor_level).ty();
798 // Visit everything, but foreign items have their own levels.
799 hir::ItemKind::ForeignMod { items, .. } => {
800 for foreign_item in items {
801 let foreign_item_level = self.get(foreign_item.id.def_id);
802 if foreign_item_level.is_some() {
803 self.reach(foreign_item.id.def_id, foreign_item_level)
810 // Visit everything except for private fields.
811 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
812 if item_level.is_some() {
813 self.reach(item.def_id, item_level).generics().predicates();
814 for field in struct_def.fields() {
815 let def_id = self.tcx.hir().local_def_id(field.hir_id);
816 let field_level = self.get(def_id);
817 if field_level.is_some() {
818 self.reach(def_id, field_level).ty();
822 if let Some(hir_id) = struct_def.ctor_hir_id() {
823 let ctor_def_id = self.tcx.hir().local_def_id(hir_id);
824 let ctor_level = self.get(ctor_def_id);
825 if ctor_level.is_some() {
826 self.reach(item.def_id, ctor_level).ty();
832 let orig_level = mem::replace(&mut self.prev_level, item_level);
833 intravisit::walk_item(self, item);
834 self.prev_level = orig_level;
837 fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
838 // Blocks can have public items, for example impls, but they always
839 // start as completely private regardless of publicity of a function,
840 // constant, type, field, etc., in which this block resides.
841 let orig_level = mem::replace(&mut self.prev_level, None);
842 intravisit::walk_block(self, b);
843 self.prev_level = orig_level;
847 impl ReachEverythingInTheInterfaceVisitor<'_, '_> {
848 fn generics(&mut self) -> &mut Self {
849 for param in &self.ev.tcx.generics_of(self.item_def_id).params {
851 GenericParamDefKind::Lifetime => {}
852 GenericParamDefKind::Type { has_default, .. } => {
854 self.visit(self.ev.tcx.type_of(param.def_id));
857 GenericParamDefKind::Const { has_default } => {
858 self.visit(self.ev.tcx.type_of(param.def_id));
860 self.visit(self.ev.tcx.const_param_default(param.def_id));
868 fn predicates(&mut self) -> &mut Self {
869 self.visit_predicates(self.ev.tcx.predicates_of(self.item_def_id));
873 fn ty(&mut self) -> &mut Self {
874 self.visit(self.ev.tcx.type_of(self.item_def_id));
878 fn trait_ref(&mut self) -> &mut Self {
879 if let Some(trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) {
880 self.visit_trait(trait_ref);
886 impl<'tcx> DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
887 fn tcx(&self) -> TyCtxt<'tcx> {
894 _descr: &dyn fmt::Display,
895 ) -> ControlFlow<Self::BreakTy> {
896 if let Some(def_id) = def_id.as_local() {
897 if let (ty::Visibility::Public, _) | (_, Some(AccessLevel::ReachableFromImplTrait)) =
898 (self.tcx().visibility(def_id.to_def_id()), self.access_level)
900 self.ev.update(def_id, self.access_level);
903 ControlFlow::CONTINUE
907 //////////////////////////////////////////////////////////////////////////////////////
908 /// Name privacy visitor, checks privacy and reports violations.
909 /// Most of name privacy checks are performed during the main resolution phase,
910 /// or later in type checking when field accesses and associated items are resolved.
911 /// This pass performs remaining checks for fields in struct expressions and patterns.
912 //////////////////////////////////////////////////////////////////////////////////////
914 struct NamePrivacyVisitor<'tcx> {
916 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
917 current_item: LocalDefId,
920 impl<'tcx> NamePrivacyVisitor<'tcx> {
921 /// Gets the type-checking results for the current body.
922 /// As this will ICE if called outside bodies, only call when working with
923 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
925 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
926 self.maybe_typeck_results
927 .expect("`NamePrivacyVisitor::typeck_results` called outside of body")
930 // Checks that a field in a struct constructor (expression or pattern) is accessible.
933 use_ctxt: Span, // syntax context of the field name at the use site
934 span: Span, // span of the field pattern, e.g., `x: 0`
935 def: ty::AdtDef<'tcx>, // definition of the struct or enum
936 field: &'tcx ty::FieldDef,
937 in_update_syntax: bool,
943 // definition of the field
944 let ident = Ident::new(kw::Empty, use_ctxt);
945 let hir_id = self.tcx.hir().local_def_id_to_hir_id(self.current_item);
946 let def_id = self.tcx.adjust_ident_and_get_scope(ident, def.did(), hir_id).1;
947 if !field.vis.is_accessible_from(def_id, self.tcx) {
948 self.tcx.sess.emit_err(FieldIsPrivate {
950 field_name: field.name,
951 variant_descr: def.variant_descr(),
952 def_path_str: self.tcx.def_path_str(def.did()),
953 label: if in_update_syntax {
954 FieldIsPrivateLabel::IsUpdateSyntax { span, field_name: field.name }
956 FieldIsPrivateLabel::Other { span }
963 impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> {
964 type NestedFilter = nested_filter::All;
966 /// We want to visit items in the context of their containing
967 /// module and so forth, so supply a crate for doing a deep walk.
968 fn nested_visit_map(&mut self) -> Self::Map {
972 fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) {
973 // Don't visit nested modules, since we run a separate visitor walk
974 // for each module in `privacy_access_levels`
977 fn visit_nested_body(&mut self, body: hir::BodyId) {
978 let old_maybe_typeck_results =
979 self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
980 let body = self.tcx.hir().body(body);
981 self.visit_body(body);
982 self.maybe_typeck_results = old_maybe_typeck_results;
985 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
986 let orig_current_item = mem::replace(&mut self.current_item, item.def_id);
987 intravisit::walk_item(self, item);
988 self.current_item = orig_current_item;
991 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
992 if let hir::ExprKind::Struct(qpath, fields, ref base) = expr.kind {
993 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
994 let adt = self.typeck_results().expr_ty(expr).ty_adt_def().unwrap();
995 let variant = adt.variant_of_res(res);
996 if let Some(base) = *base {
997 // If the expression uses FRU we need to make sure all the unmentioned fields
998 // are checked for privacy (RFC 736). Rather than computing the set of
999 // unmentioned fields, just check them all.
1000 for (vf_index, variant_field) in variant.fields.iter().enumerate() {
1001 let field = fields.iter().find(|f| {
1002 self.tcx.field_index(f.hir_id, self.typeck_results()) == vf_index
1004 let (use_ctxt, span) = match field {
1005 Some(field) => (field.ident.span, field.span),
1006 None => (base.span, base.span),
1008 self.check_field(use_ctxt, span, adt, variant_field, true);
1011 for field in fields {
1012 let use_ctxt = field.ident.span;
1013 let index = self.tcx.field_index(field.hir_id, self.typeck_results());
1014 self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false);
1019 intravisit::walk_expr(self, expr);
1022 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
1023 if let PatKind::Struct(ref qpath, fields, _) = pat.kind {
1024 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
1025 let adt = self.typeck_results().pat_ty(pat).ty_adt_def().unwrap();
1026 let variant = adt.variant_of_res(res);
1027 for field in fields {
1028 let use_ctxt = field.ident.span;
1029 let index = self.tcx.field_index(field.hir_id, self.typeck_results());
1030 self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false);
1034 intravisit::walk_pat(self, pat);
1038 ////////////////////////////////////////////////////////////////////////////////////////////
1039 /// Type privacy visitor, checks types for privacy and reports violations.
1040 /// Both explicitly written types and inferred types of expressions and patterns are checked.
1041 /// Checks are performed on "semantic" types regardless of names and their hygiene.
1042 ////////////////////////////////////////////////////////////////////////////////////////////
1044 struct TypePrivacyVisitor<'tcx> {
1046 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
1047 current_item: LocalDefId,
1051 impl<'tcx> TypePrivacyVisitor<'tcx> {
1052 /// Gets the type-checking results for the current body.
1053 /// As this will ICE if called outside bodies, only call when working with
1054 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
1056 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
1057 self.maybe_typeck_results
1058 .expect("`TypePrivacyVisitor::typeck_results` called outside of body")
1061 fn item_is_accessible(&self, did: DefId) -> bool {
1062 self.tcx.visibility(did).is_accessible_from(self.current_item.to_def_id(), self.tcx)
1065 // Take node-id of an expression or pattern and check its type for privacy.
1066 fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
1068 let typeck_results = self.typeck_results();
1069 let result: ControlFlow<()> = try {
1070 self.visit(typeck_results.node_type(id))?;
1071 self.visit(typeck_results.node_substs(id))?;
1072 if let Some(adjustments) = typeck_results.adjustments().get(id) {
1073 adjustments.iter().try_for_each(|adjustment| self.visit(adjustment.target))?;
1079 fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1080 let is_error = !self.item_is_accessible(def_id);
1082 self.tcx.sess.emit_err(ItemIsPrivate { span: self.span, kind, descr: descr.into() });
1088 impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> {
1089 type NestedFilter = nested_filter::All;
1091 /// We want to visit items in the context of their containing
1092 /// module and so forth, so supply a crate for doing a deep walk.
1093 fn nested_visit_map(&mut self) -> Self::Map {
1097 fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) {
1098 // Don't visit nested modules, since we run a separate visitor walk
1099 // for each module in `privacy_access_levels`
1102 fn visit_nested_body(&mut self, body: hir::BodyId) {
1103 let old_maybe_typeck_results =
1104 self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
1105 let body = self.tcx.hir().body(body);
1106 self.visit_body(body);
1107 self.maybe_typeck_results = old_maybe_typeck_results;
1110 fn visit_generic_arg(&mut self, generic_arg: &'tcx hir::GenericArg<'tcx>) {
1112 hir::GenericArg::Type(t) => self.visit_ty(t),
1113 hir::GenericArg::Infer(inf) => self.visit_infer(inf),
1114 hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {}
1118 fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) {
1119 self.span = hir_ty.span;
1120 if let Some(typeck_results) = self.maybe_typeck_results {
1122 if self.visit(typeck_results.node_type(hir_ty.hir_id)).is_break() {
1126 // Types in signatures.
1127 // FIXME: This is very ineffective. Ideally each HIR type should be converted
1128 // into a semantic type only once and the result should be cached somehow.
1129 if self.visit(rustc_typeck::hir_ty_to_ty(self.tcx, hir_ty)).is_break() {
1134 intravisit::walk_ty(self, hir_ty);
1137 fn visit_infer(&mut self, inf: &'tcx hir::InferArg) {
1138 self.span = inf.span;
1139 if let Some(typeck_results) = self.maybe_typeck_results {
1140 if let Some(ty) = typeck_results.node_type_opt(inf.hir_id) {
1141 if self.visit(ty).is_break() {
1145 // We don't do anything for const infers here.
1148 bug!("visit_infer without typeck_results");
1150 intravisit::walk_inf(self, inf);
1153 fn visit_trait_ref(&mut self, trait_ref: &'tcx hir::TraitRef<'tcx>) {
1154 self.span = trait_ref.path.span;
1155 if self.maybe_typeck_results.is_none() {
1156 // Avoid calling `hir_trait_to_predicates` in bodies, it will ICE.
1157 // The traits' privacy in bodies is already checked as a part of trait object types.
1158 let bounds = rustc_typeck::hir_trait_to_predicates(
1161 // NOTE: This isn't really right, but the actual type doesn't matter here. It's
1162 // just required by `ty::TraitRef`.
1163 self.tcx.types.never,
1166 for (trait_predicate, _, _) in bounds.trait_bounds {
1167 if self.visit_trait(trait_predicate.skip_binder()).is_break() {
1172 for (poly_predicate, _) in bounds.projection_bounds {
1173 let pred = poly_predicate.skip_binder();
1174 let poly_pred_term = self.visit(pred.term);
1175 if poly_pred_term.is_break()
1176 || self.visit_projection_ty(pred.projection_ty).is_break()
1183 intravisit::walk_trait_ref(self, trait_ref);
1186 // Check types of expressions
1187 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1188 if self.check_expr_pat_type(expr.hir_id, expr.span) {
1189 // Do not check nested expressions if the error already happened.
1193 hir::ExprKind::Assign(_, rhs, _) | hir::ExprKind::Match(rhs, ..) => {
1194 // Do not report duplicate errors for `x = y` and `match x { ... }`.
1195 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
1199 hir::ExprKind::MethodCall(segment, ..) => {
1200 // Method calls have to be checked specially.
1201 self.span = segment.ident.span;
1202 if let Some(def_id) = self.typeck_results().type_dependent_def_id(expr.hir_id) {
1203 if self.visit(self.tcx.type_of(def_id)).is_break() {
1209 .delay_span_bug(expr.span, "no type-dependent def for method call");
1215 intravisit::walk_expr(self, expr);
1218 // Prohibit access to associated items with insufficient nominal visibility.
1220 // Additionally, until better reachability analysis for macros 2.0 is available,
1221 // we prohibit access to private statics from other crates, this allows to give
1222 // more code internal visibility at link time. (Access to private functions
1223 // is already prohibited by type privacy for function types.)
1224 fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) {
1225 let def = match qpath {
1226 hir::QPath::Resolved(_, path) => match path.res {
1227 Res::Def(kind, def_id) => Some((kind, def_id)),
1230 hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
1231 .maybe_typeck_results
1232 .and_then(|typeck_results| typeck_results.type_dependent_def(id)),
1234 let def = def.filter(|(kind, _)| {
1237 DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static(_)
1240 if let Some((kind, def_id)) = def {
1241 let is_local_static =
1242 if let DefKind::Static(_) = kind { def_id.is_local() } else { false };
1243 if !self.item_is_accessible(def_id) && !is_local_static {
1244 let sess = self.tcx.sess;
1245 let sm = sess.source_map();
1246 let name = match qpath {
1247 hir::QPath::Resolved(..) | hir::QPath::LangItem(..) => {
1248 sm.span_to_snippet(qpath.span()).ok()
1250 hir::QPath::TypeRelative(_, segment) => Some(segment.ident.to_string()),
1252 let kind = kind.descr(def_id);
1253 let _ = match name {
1255 sess.emit_err(ItemIsPrivate { span, kind, descr: (&name).into() })
1257 None => sess.emit_err(UnnamedItemIsPrivate { span, kind }),
1263 intravisit::walk_qpath(self, qpath, id, span);
1266 // Check types of patterns.
1267 fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) {
1268 if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
1269 // Do not check nested patterns if the error already happened.
1273 intravisit::walk_pat(self, pattern);
1276 fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) {
1277 if let Some(init) = local.init {
1278 if self.check_expr_pat_type(init.hir_id, init.span) {
1279 // Do not report duplicate errors for `let x = y`.
1284 intravisit::walk_local(self, local);
1287 // Check types in item interfaces.
1288 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1289 let orig_current_item = mem::replace(&mut self.current_item, item.def_id);
1290 let old_maybe_typeck_results = self.maybe_typeck_results.take();
1291 intravisit::walk_item(self, item);
1292 self.maybe_typeck_results = old_maybe_typeck_results;
1293 self.current_item = orig_current_item;
1297 impl<'tcx> DefIdVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1298 fn tcx(&self) -> TyCtxt<'tcx> {
1305 descr: &dyn fmt::Display,
1306 ) -> ControlFlow<Self::BreakTy> {
1307 if self.check_def_id(def_id, kind, descr) {
1310 ControlFlow::CONTINUE
1315 ///////////////////////////////////////////////////////////////////////////////
1316 /// Obsolete visitors for checking for private items in public interfaces.
1317 /// These visitors are supposed to be kept in frozen state and produce an
1318 /// "old error node set". For backward compatibility the new visitor reports
1319 /// warnings instead of hard errors when the erroneous node is not in this old set.
1320 ///////////////////////////////////////////////////////////////////////////////
1322 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1324 access_levels: &'a AccessLevels,
1326 // Set of errors produced by this obsolete visitor.
1327 old_error_set: HirIdSet,
1330 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1331 inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
1332 /// Whether the type refers to private types.
1333 contains_private: bool,
1334 /// Whether we've recurred at all (i.e., if we're pointing at the
1335 /// first type on which `visit_ty` was called).
1336 at_outer_type: bool,
1337 /// Whether that first type is a public path.
1338 outer_type_is_public_path: bool,
1341 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1342 fn path_is_private_type(&self, path: &hir::Path<'_>) -> bool {
1343 let did = match path.res {
1344 Res::PrimTy(..) | Res::SelfTy { .. } | Res::Err => return false,
1345 res => res.def_id(),
1348 // A path can only be private if:
1349 // it's in this crate...
1350 if let Some(did) = did.as_local() {
1351 // .. and it corresponds to a private type in the AST (this returns
1352 // `None` for type parameters).
1353 match self.tcx.hir().find(self.tcx.hir().local_def_id_to_hir_id(did)) {
1354 Some(Node::Item(_)) => !self.tcx.visibility(did).is_public(),
1355 Some(_) | None => false,
1362 fn trait_is_public(&self, trait_id: LocalDefId) -> bool {
1363 // FIXME: this would preferably be using `exported_items`, but all
1364 // traits are exported currently (see `EmbargoVisitor.exported_trait`).
1365 self.access_levels.is_public(trait_id)
1368 fn check_generic_bound(&mut self, bound: &hir::GenericBound<'_>) {
1369 if let hir::GenericBound::Trait(ref trait_ref, _) = *bound {
1370 if self.path_is_private_type(trait_ref.trait_ref.path) {
1371 self.old_error_set.insert(trait_ref.trait_ref.hir_ref_id);
1376 fn item_is_public(&self, def_id: LocalDefId) -> bool {
1377 self.access_levels.is_reachable(def_id) || self.tcx.visibility(def_id).is_public()
1381 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1382 fn visit_generic_arg(&mut self, generic_arg: &'v hir::GenericArg<'v>) {
1384 hir::GenericArg::Type(t) => self.visit_ty(t),
1385 hir::GenericArg::Infer(inf) => self.visit_ty(&inf.to_ty()),
1386 hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {}
1390 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
1391 if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = ty.kind {
1392 if self.inner.path_is_private_type(path) {
1393 self.contains_private = true;
1394 // Found what we're looking for, so let's stop working.
1398 if let hir::TyKind::Path(_) = ty.kind {
1399 if self.at_outer_type {
1400 self.outer_type_is_public_path = true;
1403 self.at_outer_type = false;
1404 intravisit::walk_ty(self, ty)
1407 // Don't want to recurse into `[, .. expr]`.
1408 fn visit_expr(&mut self, _: &hir::Expr<'_>) {}
1411 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1412 type NestedFilter = nested_filter::All;
1414 /// We want to visit items in the context of their containing
1415 /// module and so forth, so supply a crate for doing a deep walk.
1416 fn nested_visit_map(&mut self) -> Self::Map {
1420 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1422 // Contents of a private mod can be re-exported, so we need
1423 // to check internals.
1424 hir::ItemKind::Mod(_) => {}
1426 // An `extern {}` doesn't introduce a new privacy
1427 // namespace (the contents have their own privacies).
1428 hir::ItemKind::ForeignMod { .. } => {}
1430 hir::ItemKind::Trait(.., bounds, _) => {
1431 if !self.trait_is_public(item.def_id) {
1435 for bound in bounds.iter() {
1436 self.check_generic_bound(bound)
1440 // Impls need some special handling to try to offer useful
1441 // error messages without (too many) false positives
1442 // (i.e., we could just return here to not check them at
1443 // all, or some worse estimation of whether an impl is
1444 // publicly visible).
1445 hir::ItemKind::Impl(ref impl_) => {
1446 // `impl [... for] Private` is never visible.
1447 let self_contains_private;
1448 // `impl [... for] Public<...>`, but not `impl [... for]
1449 // Vec<Public>` or `(Public,)`, etc.
1450 let self_is_public_path;
1452 // Check the properties of the `Self` type:
1454 let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
1456 contains_private: false,
1457 at_outer_type: true,
1458 outer_type_is_public_path: false,
1460 visitor.visit_ty(impl_.self_ty);
1461 self_contains_private = visitor.contains_private;
1462 self_is_public_path = visitor.outer_type_is_public_path;
1465 // Miscellaneous info about the impl:
1467 // `true` iff this is `impl Private for ...`.
1468 let not_private_trait = impl_.of_trait.as_ref().map_or(
1469 true, // no trait counts as public trait
1471 if let Some(def_id) = tr.path.res.def_id().as_local() {
1472 self.trait_is_public(def_id)
1474 true // external traits must be public
1479 // `true` iff this is a trait impl or at least one method is public.
1481 // `impl Public { $( fn ...() {} )* }` is not visible.
1483 // This is required over just using the methods' privacy
1484 // directly because we might have `impl<T: Foo<Private>> ...`,
1485 // and we shouldn't warn about the generics if all the methods
1486 // are private (because `T` won't be visible externally).
1487 let trait_or_some_public_method = impl_.of_trait.is_some()
1488 || impl_.items.iter().any(|impl_item_ref| {
1489 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1490 match impl_item.kind {
1491 hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) => {
1492 self.access_levels.is_reachable(impl_item_ref.id.def_id)
1494 hir::ImplItemKind::TyAlias(_) => false,
1498 if !self_contains_private && not_private_trait && trait_or_some_public_method {
1499 intravisit::walk_generics(self, &impl_.generics);
1501 match impl_.of_trait {
1503 for impl_item_ref in impl_.items {
1504 // This is where we choose whether to walk down
1505 // further into the impl to check its items. We
1506 // should only walk into public items so that we
1507 // don't erroneously report errors for private
1508 // types in private items.
1509 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1510 match impl_item.kind {
1511 hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..)
1512 if self.item_is_public(impl_item.def_id) =>
1514 intravisit::walk_impl_item(self, impl_item)
1516 hir::ImplItemKind::TyAlias(..) => {
1517 intravisit::walk_impl_item(self, impl_item)
1524 // Any private types in a trait impl fall into three
1526 // 1. mentioned in the trait definition
1527 // 2. mentioned in the type params/generics
1528 // 3. mentioned in the associated types of the impl
1530 // Those in 1. can only occur if the trait is in
1531 // this crate and will have been warned about on the
1532 // trait definition (there's no need to warn twice
1533 // so we don't check the methods).
1535 // Those in 2. are warned via walk_generics and this
1537 intravisit::walk_path(self, tr.path);
1539 // Those in 3. are warned with this call.
1540 for impl_item_ref in impl_.items {
1541 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1542 if let hir::ImplItemKind::TyAlias(ty) = impl_item.kind {
1548 } else if impl_.of_trait.is_none() && self_is_public_path {
1549 // `impl Public<Private> { ... }`. Any public static
1550 // methods will be visible as `Public::foo`.
1551 let mut found_pub_static = false;
1552 for impl_item_ref in impl_.items {
1553 if self.access_levels.is_reachable(impl_item_ref.id.def_id)
1554 || self.tcx.visibility(impl_item_ref.id.def_id)
1555 == ty::Visibility::Public
1557 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1558 match impl_item_ref.kind {
1559 AssocItemKind::Const => {
1560 found_pub_static = true;
1561 intravisit::walk_impl_item(self, impl_item);
1563 AssocItemKind::Fn { has_self: false } => {
1564 found_pub_static = true;
1565 intravisit::walk_impl_item(self, impl_item);
1571 if found_pub_static {
1572 intravisit::walk_generics(self, &impl_.generics)
1578 // `type ... = ...;` can contain private types, because
1579 // we're introducing a new name.
1580 hir::ItemKind::TyAlias(..) => return,
1582 // Not at all public, so we don't care.
1583 _ if !self.item_is_public(item.def_id) => {
1590 // We've carefully constructed it so that if we're here, then
1591 // any `visit_ty`'s will be called on things that are in
1592 // public signatures, i.e., things that we're interested in for
1594 intravisit::walk_item(self, item);
1597 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1598 for predicate in generics.predicates {
1600 hir::WherePredicate::BoundPredicate(bound_pred) => {
1601 for bound in bound_pred.bounds.iter() {
1602 self.check_generic_bound(bound)
1605 hir::WherePredicate::RegionPredicate(_) => {}
1606 hir::WherePredicate::EqPredicate(eq_pred) => {
1607 self.visit_ty(eq_pred.rhs_ty);
1613 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
1614 if self.access_levels.is_reachable(item.def_id) {
1615 intravisit::walk_foreign_item(self, item)
1619 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
1620 if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = t.kind {
1621 if self.path_is_private_type(path) {
1622 self.old_error_set.insert(t.hir_id);
1625 intravisit::walk_ty(self, t)
1628 fn visit_variant(&mut self, v: &'tcx hir::Variant<'tcx>) {
1629 if self.access_levels.is_reachable(self.tcx.hir().local_def_id(v.id)) {
1630 self.in_variant = true;
1631 intravisit::walk_variant(self, v);
1632 self.in_variant = false;
1636 fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) {
1637 let def_id = self.tcx.hir().local_def_id(s.hir_id);
1638 let vis = self.tcx.visibility(def_id);
1639 if vis.is_public() || self.in_variant {
1640 intravisit::walk_field_def(self, s);
1644 // We don't need to introspect into these at all: an
1645 // expression/block context can't possibly contain exported things.
1646 // (Making them no-ops stops us from traversing the whole AST without
1647 // having to be super careful about our `walk_...` calls above.)
1648 fn visit_block(&mut self, _: &'tcx hir::Block<'tcx>) {}
1649 fn visit_expr(&mut self, _: &'tcx hir::Expr<'tcx>) {}
1652 ///////////////////////////////////////////////////////////////////////////////
1653 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1654 /// finds any private components in it.
1655 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1656 /// and traits in public interfaces.
1657 ///////////////////////////////////////////////////////////////////////////////
1659 struct SearchInterfaceForPrivateItemsVisitor<'tcx> {
1661 item_def_id: LocalDefId,
1662 /// The visitor checks that each component type is at least this visible.
1663 required_visibility: ty::Visibility,
1664 has_old_errors: bool,
1668 impl SearchInterfaceForPrivateItemsVisitor<'_> {
1669 fn generics(&mut self) -> &mut Self {
1670 for param in &self.tcx.generics_of(self.item_def_id).params {
1672 GenericParamDefKind::Lifetime => {}
1673 GenericParamDefKind::Type { has_default, .. } => {
1675 self.visit(self.tcx.type_of(param.def_id));
1678 // FIXME(generic_const_exprs): May want to look inside const here
1679 GenericParamDefKind::Const { .. } => {
1680 self.visit(self.tcx.type_of(param.def_id));
1687 fn predicates(&mut self) -> &mut Self {
1688 // N.B., we use `explicit_predicates_of` and not `predicates_of`
1689 // because we don't want to report privacy errors due to where
1690 // clauses that the compiler inferred. We only want to
1691 // consider the ones that the user wrote. This is important
1692 // for the inferred outlives rules; see
1693 // `src/test/ui/rfc-2093-infer-outlives/privacy.rs`.
1694 self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id));
1698 fn bounds(&mut self) -> &mut Self {
1699 self.visit_predicates(ty::GenericPredicates {
1701 predicates: self.tcx.explicit_item_bounds(self.item_def_id),
1706 fn ty(&mut self) -> &mut Self {
1707 self.visit(self.tcx.type_of(self.item_def_id));
1711 fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1712 if self.leaks_private_dep(def_id) {
1713 self.tcx.emit_spanned_lint(
1714 lint::builtin::EXPORTED_PRIVATE_DEPENDENCIES,
1715 self.tcx.hir().local_def_id_to_hir_id(self.item_def_id),
1716 self.tcx.def_span(self.item_def_id.to_def_id()),
1717 FromPrivateDependencyInPublicInterface {
1719 descr: descr.into(),
1720 krate: self.tcx.crate_name(def_id.krate),
1725 let hir_id = match def_id.as_local() {
1726 Some(def_id) => self.tcx.hir().local_def_id_to_hir_id(def_id),
1727 None => return false,
1730 let vis = self.tcx.visibility(def_id);
1731 if !vis.is_at_least(self.required_visibility, self.tcx) {
1732 let vis_descr = match vis {
1733 ty::Visibility::Public => "public",
1734 ty::Visibility::Invisible => "private",
1735 ty::Visibility::Restricted(vis_def_id) => {
1736 if vis_def_id == self.tcx.parent_module(hir_id).to_def_id() {
1738 } else if vis_def_id.is_top_level_module() {
1745 let span = self.tcx.def_span(self.item_def_id.to_def_id());
1746 if self.has_old_errors
1748 || self.tcx.resolutions(()).has_pub_restricted
1750 let vis_span = self.tcx.def_span(def_id);
1751 if kind == "trait" {
1752 self.tcx.sess.emit_err(InPublicInterfaceTraits {
1756 descr: descr.into(),
1760 self.tcx.sess.emit_err(InPublicInterface {
1764 descr: descr.into(),
1769 self.tcx.emit_spanned_lint(
1770 lint::builtin::PRIVATE_IN_PUBLIC,
1773 PrivateInPublicLint { vis_descr, kind, descr: descr.into() },
1781 /// An item is 'leaked' from a private dependency if all
1782 /// of the following are true:
1783 /// 1. It's contained within a public type
1784 /// 2. It comes from a private crate
1785 fn leaks_private_dep(&self, item_id: DefId) -> bool {
1786 let ret = self.required_visibility.is_public() && self.tcx.is_private_dep(item_id.krate);
1788 tracing::debug!("leaks_private_dep(item_id={:?})={}", item_id, ret);
1793 impl<'tcx> DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> {
1794 fn tcx(&self) -> TyCtxt<'tcx> {
1801 descr: &dyn fmt::Display,
1802 ) -> ControlFlow<Self::BreakTy> {
1803 if self.check_def_id(def_id, kind, descr) {
1806 ControlFlow::CONTINUE
1811 struct PrivateItemsInPublicInterfacesChecker<'tcx> {
1813 old_error_set_ancestry: LocalDefIdSet,
1816 impl<'tcx> PrivateItemsInPublicInterfacesChecker<'tcx> {
1820 required_visibility: ty::Visibility,
1821 ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> {
1822 SearchInterfaceForPrivateItemsVisitor {
1824 item_def_id: def_id,
1825 required_visibility,
1826 has_old_errors: self.old_error_set_ancestry.contains(&def_id),
1831 fn check_assoc_item(
1834 assoc_item_kind: AssocItemKind,
1835 vis: ty::Visibility,
1837 let mut check = self.check(def_id, vis);
1839 let (check_ty, is_assoc_ty) = match assoc_item_kind {
1840 AssocItemKind::Const | AssocItemKind::Fn { .. } => (true, false),
1841 AssocItemKind::Type => (self.tcx.impl_defaultness(def_id).has_value(), true),
1843 check.in_assoc_ty = is_assoc_ty;
1844 check.generics().predicates();
1850 pub fn check_item(&mut self, id: ItemId) {
1852 let item_visibility = tcx.visibility(id.def_id);
1853 let def_kind = tcx.def_kind(id.def_id);
1856 DefKind::Const | DefKind::Static(_) | DefKind::Fn | DefKind::TyAlias => {
1857 self.check(id.def_id, item_visibility).generics().predicates().ty();
1859 DefKind::OpaqueTy => {
1860 // `ty()` for opaque types is the underlying type,
1861 // it's not a part of interface, so we skip it.
1862 self.check(id.def_id, item_visibility).generics().bounds();
1865 let item = tcx.hir().item(id);
1866 if let hir::ItemKind::Trait(.., trait_item_refs) = item.kind {
1867 self.check(item.def_id, item_visibility).generics().predicates();
1869 for trait_item_ref in trait_item_refs {
1870 self.check_assoc_item(
1871 trait_item_ref.id.def_id,
1872 trait_item_ref.kind,
1876 if let AssocItemKind::Type = trait_item_ref.kind {
1877 self.check(trait_item_ref.id.def_id, item_visibility).bounds();
1882 DefKind::TraitAlias => {
1883 self.check(id.def_id, item_visibility).generics().predicates();
1886 let item = tcx.hir().item(id);
1887 if let hir::ItemKind::Enum(ref def, _) = item.kind {
1888 self.check(item.def_id, item_visibility).generics().predicates();
1890 for variant in def.variants {
1891 for field in variant.data.fields() {
1892 self.check(self.tcx.hir().local_def_id(field.hir_id), item_visibility)
1898 // Subitems of foreign modules have their own publicity.
1899 DefKind::ForeignMod => {
1900 let item = tcx.hir().item(id);
1901 if let hir::ItemKind::ForeignMod { items, .. } = item.kind {
1902 for foreign_item in items {
1903 let vis = tcx.visibility(foreign_item.id.def_id);
1904 self.check(foreign_item.id.def_id, vis).generics().predicates().ty();
1908 // Subitems of structs and unions have their own publicity.
1909 DefKind::Struct | DefKind::Union => {
1910 let item = tcx.hir().item(id);
1911 if let hir::ItemKind::Struct(ref struct_def, _)
1912 | hir::ItemKind::Union(ref struct_def, _) = item.kind
1914 self.check(item.def_id, item_visibility).generics().predicates();
1916 for field in struct_def.fields() {
1917 let def_id = tcx.hir().local_def_id(field.hir_id);
1918 let field_visibility = tcx.visibility(def_id);
1919 self.check(def_id, min(item_visibility, field_visibility, tcx)).ty();
1923 // An inherent impl is public when its type is public
1924 // Subitems of inherent impls have their own publicity.
1925 // A trait impl is public when both its type and its trait are public
1926 // Subitems of trait impls have inherited publicity.
1928 let item = tcx.hir().item(id);
1929 if let hir::ItemKind::Impl(ref impl_) = item.kind {
1930 let impl_vis = ty::Visibility::of_impl(item.def_id, tcx, &Default::default());
1931 // check that private components do not appear in the generics or predicates of inherent impls
1932 // this check is intentionally NOT performed for impls of traits, per #90586
1933 if impl_.of_trait.is_none() {
1934 self.check(item.def_id, impl_vis).generics().predicates();
1936 for impl_item_ref in impl_.items {
1937 let impl_item_vis = if impl_.of_trait.is_none() {
1938 min(tcx.visibility(impl_item_ref.id.def_id), impl_vis, tcx)
1942 self.check_assoc_item(
1943 impl_item_ref.id.def_id,
1955 pub fn provide(providers: &mut Providers) {
1956 *providers = Providers {
1958 privacy_access_levels,
1959 check_private_in_public,
1965 fn visibility(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Visibility {
1966 let def_id = def_id.expect_local();
1967 match tcx.resolutions(()).visibilities.get(&def_id) {
1970 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1971 match tcx.hir().get(hir_id) {
1972 // Unique types created for closures participate in type privacy checking.
1973 // They have visibilities inherited from the module they are defined in.
1974 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure{..}, .. })
1975 // - AST lowering creates dummy `use` items which don't
1976 // get their entries in the resolver's visibility table.
1977 // - AST lowering also creates opaque type items with inherited visibilities.
1978 // Visibility on them should have no effect, but to avoid the visibility
1979 // query failing on some items, we provide it for opaque types as well.
1980 | Node::Item(hir::Item {
1981 kind: hir::ItemKind::Use(_, hir::UseKind::ListStem) | hir::ItemKind::OpaqueTy(..),
1983 }) => ty::Visibility::Restricted(tcx.parent_module(hir_id).to_def_id()),
1984 // Visibilities of trait impl items are inherited from their traits
1985 // and are not filled in resolve.
1986 Node::ImplItem(impl_item) => {
1987 match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(hir_id)) {
1988 Node::Item(hir::Item {
1989 kind: hir::ItemKind::Impl(hir::Impl { of_trait: Some(tr), .. }),
1991 }) => tr.path.res.opt_def_id().map_or_else(
1993 tcx.sess.delay_span_bug(tr.path.span, "trait without a def-id");
1994 ty::Visibility::Public
1996 |def_id| tcx.visibility(def_id),
1998 _ => span_bug!(impl_item.span, "the parent is not a trait impl"),
2002 tcx.def_span(def_id),
2003 "visibility table unexpectedly missing a def-id: {:?}",
2011 fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
2012 // Check privacy of names not checked in previous compilation stages.
2014 NamePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id };
2015 let (module, span, hir_id) = tcx.hir().get_module(module_def_id);
2017 intravisit::walk_mod(&mut visitor, module, hir_id);
2019 // Check privacy of explicitly written types and traits as well as
2020 // inferred types of expressions and patterns.
2022 TypePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id, span };
2023 intravisit::walk_mod(&mut visitor, module, hir_id);
2026 fn privacy_access_levels(tcx: TyCtxt<'_>, (): ()) -> &AccessLevels {
2027 // Build up a set of all exported items in the AST. This is a set of all
2028 // items which are reachable from external crates based on visibility.
2029 let mut visitor = EmbargoVisitor {
2031 access_levels: tcx.resolutions(()).access_levels.clone(),
2032 macro_reachable: Default::default(),
2033 prev_level: Some(AccessLevel::Public),
2038 tcx.hir().walk_toplevel_module(&mut visitor);
2039 if visitor.changed {
2040 visitor.changed = false;
2046 tcx.arena.alloc(visitor.access_levels)
2049 fn check_private_in_public(tcx: TyCtxt<'_>, (): ()) {
2050 let access_levels = tcx.privacy_access_levels(());
2052 let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
2056 old_error_set: Default::default(),
2058 tcx.hir().walk_toplevel_module(&mut visitor);
2060 let mut old_error_set_ancestry = HirIdSet::default();
2061 for mut id in visitor.old_error_set.iter().copied() {
2063 if !old_error_set_ancestry.insert(id) {
2066 let parent = tcx.hir().get_parent_node(id);
2074 // Check for private types and traits in public interfaces.
2075 let mut checker = PrivateItemsInPublicInterfacesChecker {
2077 // Only definition IDs are ever searched in `old_error_set_ancestry`,
2078 // so we can filter away all non-definition IDs at this point.
2079 old_error_set_ancestry: old_error_set_ancestry
2081 .filter_map(|hir_id| tcx.hir().opt_local_def_id(hir_id))
2085 for id in tcx.hir().items() {
2086 checker.check_item(id);