1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
2 #![feature(control_flow_enum)]
3 #![feature(try_blocks)]
4 #![feature(associated_type_defaults)]
5 #![recursion_limit = "256"]
6 #![allow(rustc::potential_query_instability)]
10 use rustc_ast::MacroDef;
11 use rustc_attr as attr;
12 use rustc_data_structures::fx::FxHashSet;
13 use rustc_data_structures::intern::Interned;
14 use rustc_errors::struct_span_err;
16 use rustc_hir::def::{DefKind, Res};
17 use rustc_hir::def_id::{DefId, LocalDefId, LocalDefIdSet, CRATE_DEF_ID};
18 use rustc_hir::intravisit::{self, Visitor};
19 use rustc_hir::{AssocItemKind, HirIdSet, ItemId, Node, PatKind};
20 use rustc_middle::bug;
21 use rustc_middle::hir::nested_filter;
22 use rustc_middle::middle::privacy::{AccessLevel, AccessLevels};
23 use rustc_middle::span_bug;
24 use rustc_middle::thir::abstract_const::Node as ACNode;
25 use rustc_middle::ty::query::Providers;
26 use rustc_middle::ty::subst::InternalSubsts;
27 use rustc_middle::ty::{self, Const, DefIdTree, GenericParamDefKind};
28 use rustc_middle::ty::{TraitRef, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable, TypeVisitor};
29 use rustc_session::lint;
30 use rustc_span::hygiene::Transparency;
31 use rustc_span::symbol::{kw, Ident};
33 use rustc_trait_selection::traits::const_evaluatable::{self, AbstractConst};
35 use std::marker::PhantomData;
36 use std::ops::ControlFlow;
37 use std::{cmp, fmt, mem};
39 use errors::{FieldIsPrivate, FieldIsPrivateLabel, ItemIsPrivate, UnnamedItemIsPrivate};
41 ////////////////////////////////////////////////////////////////////////////////
42 /// Generic infrastructure used to implement specific visitors below.
43 ////////////////////////////////////////////////////////////////////////////////
45 /// Implemented to visit all `DefId`s in a type.
46 /// Visiting `DefId`s is useful because visibilities and reachabilities are attached to them.
47 /// The idea is to visit "all components of a type", as documented in
48 /// <https://github.com/rust-lang/rfcs/blob/master/text/2145-type-privacy.md#how-to-determine-visibility-of-a-type>.
49 /// The default type visitor (`TypeVisitor`) does most of the job, but it has some shortcomings.
50 /// First, it doesn't have overridable `fn visit_trait_ref`, so we have to catch trait `DefId`s
51 /// manually. Second, it doesn't visit some type components like signatures of fn types, or traits
52 /// in `impl Trait`, see individual comments in `DefIdVisitorSkeleton::visit_ty`.
53 trait DefIdVisitor<'tcx> {
56 fn tcx(&self) -> TyCtxt<'tcx>;
57 fn shallow(&self) -> bool {
60 fn skip_assoc_tys(&self) -> bool {
67 descr: &dyn fmt::Display,
68 ) -> ControlFlow<Self::BreakTy>;
70 /// Not overridden, but used to actually visit types and traits.
71 fn skeleton(&mut self) -> DefIdVisitorSkeleton<'_, 'tcx, Self> {
72 DefIdVisitorSkeleton {
74 visited_opaque_tys: Default::default(),
75 dummy: Default::default(),
78 fn visit(&mut self, ty_fragment: impl TypeFoldable<'tcx>) -> ControlFlow<Self::BreakTy> {
79 ty_fragment.visit_with(&mut self.skeleton())
81 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> ControlFlow<Self::BreakTy> {
82 self.skeleton().visit_trait(trait_ref)
84 fn visit_projection_ty(
86 projection: ty::ProjectionTy<'tcx>,
87 ) -> ControlFlow<Self::BreakTy> {
88 self.skeleton().visit_projection_ty(projection)
92 predicates: ty::GenericPredicates<'tcx>,
93 ) -> ControlFlow<Self::BreakTy> {
94 self.skeleton().visit_predicates(predicates)
98 struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> {
99 def_id_visitor: &'v mut V,
100 visited_opaque_tys: FxHashSet<DefId>,
101 dummy: PhantomData<TyCtxt<'tcx>>,
104 impl<'tcx, V> DefIdVisitorSkeleton<'_, 'tcx, V>
106 V: DefIdVisitor<'tcx> + ?Sized,
108 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> ControlFlow<V::BreakTy> {
109 let TraitRef { def_id, substs } = trait_ref;
110 self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref.print_only_trait_path())?;
111 if self.def_id_visitor.shallow() { ControlFlow::CONTINUE } else { substs.visit_with(self) }
114 fn visit_projection_ty(
116 projection: ty::ProjectionTy<'tcx>,
117 ) -> ControlFlow<V::BreakTy> {
118 let (trait_ref, assoc_substs) =
119 projection.trait_ref_and_own_substs(self.def_id_visitor.tcx());
120 self.visit_trait(trait_ref)?;
121 if self.def_id_visitor.shallow() {
122 ControlFlow::CONTINUE
124 assoc_substs.iter().try_for_each(|subst| subst.visit_with(self))
128 fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<V::BreakTy> {
129 match predicate.kind().skip_binder() {
130 ty::PredicateKind::Trait(ty::TraitPredicate {
134 }) => self.visit_trait(trait_ref),
135 ty::PredicateKind::Projection(ty::ProjectionPredicate { projection_ty, term }) => {
136 term.visit_with(self)?;
137 self.visit_projection_ty(projection_ty)
139 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _region)) => {
142 ty::PredicateKind::RegionOutlives(..) => ControlFlow::CONTINUE,
143 ty::PredicateKind::ConstEvaluatable(uv)
144 if self.def_id_visitor.tcx().features().generic_const_exprs =>
146 let tcx = self.def_id_visitor.tcx();
147 if let Ok(Some(ct)) = AbstractConst::new(tcx, uv) {
148 self.visit_abstract_const_expr(tcx, ct)?;
150 ControlFlow::CONTINUE
152 _ => bug!("unexpected predicate: {:?}", predicate),
156 fn visit_abstract_const_expr(
159 ct: AbstractConst<'tcx>,
160 ) -> ControlFlow<V::BreakTy> {
161 const_evaluatable::walk_abstract_const(tcx, ct, |node| match node.root(tcx) {
162 ACNode::Leaf(leaf) => self.visit_const(leaf),
163 ACNode::Cast(_, _, ty) => self.visit_ty(ty),
164 ACNode::Binop(..) | ACNode::UnaryOp(..) | ACNode::FunctionCall(_, _) => {
165 ControlFlow::CONTINUE
172 predicates: ty::GenericPredicates<'tcx>,
173 ) -> ControlFlow<V::BreakTy> {
174 let ty::GenericPredicates { parent: _, predicates } = predicates;
175 predicates.iter().try_for_each(|&(predicate, _span)| self.visit_predicate(predicate))
179 impl<'tcx, V> TypeVisitor<'tcx> for DefIdVisitorSkeleton<'_, 'tcx, V>
181 V: DefIdVisitor<'tcx> + ?Sized,
183 type BreakTy = V::BreakTy;
185 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<V::BreakTy> {
186 let tcx = self.def_id_visitor.tcx();
187 // InternalSubsts are not visited here because they are visited below
188 // in `super_visit_with`.
190 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), ..)
191 | ty::Foreign(def_id)
192 | ty::FnDef(def_id, ..)
193 | ty::Closure(def_id, ..)
194 | ty::Generator(def_id, ..) => {
195 self.def_id_visitor.visit_def_id(def_id, "type", &ty)?;
196 if self.def_id_visitor.shallow() {
197 return ControlFlow::CONTINUE;
199 // Default type visitor doesn't visit signatures of fn types.
200 // Something like `fn() -> Priv {my_func}` is considered a private type even if
201 // `my_func` is public, so we need to visit signatures.
202 if let ty::FnDef(..) = ty.kind() {
203 tcx.fn_sig(def_id).visit_with(self)?;
205 // Inherent static methods don't have self type in substs.
206 // Something like `fn() {my_method}` type of the method
207 // `impl Pub<Priv> { pub fn my_method() {} }` is considered a private type,
208 // so we need to visit the self type additionally.
209 if let Some(assoc_item) = tcx.opt_associated_item(def_id) {
210 if let ty::ImplContainer(impl_def_id) = assoc_item.container {
211 tcx.type_of(impl_def_id).visit_with(self)?;
215 ty::Projection(proj) => {
216 if self.def_id_visitor.skip_assoc_tys() {
217 // Visitors searching for minimal visibility/reachability want to
218 // conservatively approximate associated types like `<Type as Trait>::Alias`
219 // as visible/reachable even if both `Type` and `Trait` are private.
220 // Ideally, associated types should be substituted in the same way as
221 // free type aliases, but this isn't done yet.
222 return ControlFlow::CONTINUE;
224 // This will also visit substs if necessary, so we don't need to recurse.
225 return self.visit_projection_ty(proj);
227 ty::Dynamic(predicates, ..) => {
228 // All traits in the list are considered the "primary" part of the type
229 // and are visited by shallow visitors.
230 for predicate in predicates {
231 let trait_ref = match predicate.skip_binder() {
232 ty::ExistentialPredicate::Trait(trait_ref) => trait_ref,
233 ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx),
234 ty::ExistentialPredicate::AutoTrait(def_id) => {
235 ty::ExistentialTraitRef { def_id, substs: InternalSubsts::empty() }
238 let ty::ExistentialTraitRef { def_id, substs: _ } = trait_ref;
239 self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref)?;
242 ty::Opaque(def_id, ..) => {
243 // Skip repeated `Opaque`s to avoid infinite recursion.
244 if self.visited_opaque_tys.insert(def_id) {
245 // The intent is to treat `impl Trait1 + Trait2` identically to
246 // `dyn Trait1 + Trait2`. Therefore we ignore def-id of the opaque type itself
247 // (it either has no visibility, or its visibility is insignificant, like
248 // visibilities of type aliases) and recurse into bounds instead to go
249 // through the trait list (default type visitor doesn't visit those traits).
250 // All traits in the list are considered the "primary" part of the type
251 // and are visited by shallow visitors.
252 self.visit_predicates(ty::GenericPredicates {
254 predicates: tcx.explicit_item_bounds(def_id),
258 // These types don't have their own def-ids (but may have subcomponents
259 // with def-ids that should be visited recursively).
275 | ty::GeneratorWitness(..) => {}
276 ty::Bound(..) | ty::Placeholder(..) | ty::Infer(..) => {
277 bug!("unexpected type: {:?}", ty)
281 if self.def_id_visitor.shallow() {
282 ControlFlow::CONTINUE
284 ty.super_visit_with(self)
288 fn visit_const(&mut self, c: Const<'tcx>) -> ControlFlow<Self::BreakTy> {
289 self.visit_ty(c.ty())?;
290 let tcx = self.def_id_visitor.tcx();
291 if let Ok(Some(ct)) = AbstractConst::from_const(tcx, c) {
292 self.visit_abstract_const_expr(tcx, ct)?;
294 ControlFlow::CONTINUE
298 fn min(vis1: ty::Visibility, vis2: ty::Visibility, tcx: TyCtxt<'_>) -> ty::Visibility {
299 if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
302 ////////////////////////////////////////////////////////////////////////////////
303 /// Visitor used to determine impl visibility and reachability.
304 ////////////////////////////////////////////////////////////////////////////////
306 struct FindMin<'a, 'tcx, VL: VisibilityLike> {
308 access_levels: &'a AccessLevels,
312 impl<'a, 'tcx, VL: VisibilityLike> DefIdVisitor<'tcx> for FindMin<'a, 'tcx, VL> {
313 fn tcx(&self) -> TyCtxt<'tcx> {
316 fn shallow(&self) -> bool {
319 fn skip_assoc_tys(&self) -> bool {
326 _descr: &dyn fmt::Display,
327 ) -> ControlFlow<Self::BreakTy> {
328 self.min = VL::new_min(self, def_id);
329 ControlFlow::CONTINUE
333 trait VisibilityLike: Sized {
335 const SHALLOW: bool = false;
336 fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self;
338 // Returns an over-approximation (`skip_assoc_tys` = true) of visibility due to
339 // associated types for which we can't determine visibility precisely.
340 fn of_impl(def_id: LocalDefId, tcx: TyCtxt<'_>, access_levels: &AccessLevels) -> Self {
341 let mut find = FindMin { tcx, access_levels, min: Self::MAX };
342 find.visit(tcx.type_of(def_id));
343 if let Some(trait_ref) = tcx.impl_trait_ref(def_id) {
344 find.visit_trait(trait_ref);
349 impl VisibilityLike for ty::Visibility {
350 const MAX: Self = ty::Visibility::Public;
351 fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self {
352 min(find.tcx.visibility(def_id), find.min, find.tcx)
355 impl VisibilityLike for Option<AccessLevel> {
356 const MAX: Self = Some(AccessLevel::Public);
357 // Type inference is very smart sometimes.
358 // It can make an impl reachable even some components of its type or trait are unreachable.
359 // E.g. methods of `impl ReachableTrait<UnreachableTy> for ReachableTy<UnreachableTy> { ... }`
360 // can be usable from other crates (#57264). So we skip substs when calculating reachability
361 // and consider an impl reachable if its "shallow" type and trait are reachable.
363 // The assumption we make here is that type-inference won't let you use an impl without knowing
364 // both "shallow" version of its self type and "shallow" version of its trait if it exists
365 // (which require reaching the `DefId`s in them).
366 const SHALLOW: bool = true;
367 fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self {
369 if let Some(def_id) = def_id.as_local() {
370 find.access_levels.map.get(&def_id).copied()
379 ////////////////////////////////////////////////////////////////////////////////
380 /// The embargo visitor, used to determine the exports of the AST.
381 ////////////////////////////////////////////////////////////////////////////////
383 struct EmbargoVisitor<'tcx> {
386 /// Accessibility levels for reachable nodes.
387 access_levels: AccessLevels,
388 /// A set of pairs corresponding to modules, where the first module is
389 /// reachable via a macro that's defined in the second module. This cannot
390 /// be represented as reachable because it can't handle the following case:
392 /// pub mod n { // Should be `Public`
393 /// pub(crate) mod p { // Should *not* be accessible
394 /// pub fn f() -> i32 { 12 } // Must be `Reachable`
400 macro_reachable: FxHashSet<(LocalDefId, LocalDefId)>,
401 /// Previous accessibility level; `None` means unreachable.
402 prev_level: Option<AccessLevel>,
403 /// Has something changed in the level map?
407 struct ReachEverythingInTheInterfaceVisitor<'a, 'tcx> {
408 access_level: Option<AccessLevel>,
409 item_def_id: LocalDefId,
410 ev: &'a mut EmbargoVisitor<'tcx>,
413 impl<'tcx> EmbargoVisitor<'tcx> {
414 fn get(&self, def_id: LocalDefId) -> Option<AccessLevel> {
415 self.access_levels.map.get(&def_id).copied()
418 fn update_with_hir_id(
421 level: Option<AccessLevel>,
422 ) -> Option<AccessLevel> {
423 let def_id = self.tcx.hir().local_def_id(hir_id);
424 self.update(def_id, level)
427 /// Updates node level and returns the updated level.
428 fn update(&mut self, def_id: LocalDefId, level: Option<AccessLevel>) -> Option<AccessLevel> {
429 let old_level = self.get(def_id);
430 // Accessibility levels can only grow.
431 if level > old_level {
432 self.access_levels.map.insert(def_id, level.unwrap());
443 access_level: Option<AccessLevel>,
444 ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
445 ReachEverythingInTheInterfaceVisitor {
446 access_level: cmp::min(access_level, Some(AccessLevel::Reachable)),
452 // We have to make sure that the items that macros might reference
453 // are reachable, since they might be exported transitively.
454 fn update_reachability_from_macro(&mut self, local_def_id: LocalDefId, md: &MacroDef) {
455 // Non-opaque macros cannot make other items more accessible than they already are.
457 let hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
458 let attrs = self.tcx.hir().attrs(hir_id);
459 if attr::find_transparency(attrs, md.macro_rules).0 != Transparency::Opaque {
463 let macro_module_def_id = self.tcx.local_parent(local_def_id);
464 if self.tcx.hir().opt_def_kind(macro_module_def_id) != Some(DefKind::Mod) {
465 // The macro's parent doesn't correspond to a `mod`, return early (#63164, #65252).
469 if self.get(local_def_id).is_none() {
473 // Since we are starting from an externally visible module,
474 // all the parents in the loop below are also guaranteed to be modules.
475 let mut module_def_id = macro_module_def_id;
477 let changed_reachability =
478 self.update_macro_reachable(module_def_id, macro_module_def_id);
479 if changed_reachability || module_def_id == CRATE_DEF_ID {
482 module_def_id = self.tcx.local_parent(module_def_id);
486 /// Updates the item as being reachable through a macro defined in the given
487 /// module. Returns `true` if the level has changed.
488 fn update_macro_reachable(
490 module_def_id: LocalDefId,
491 defining_mod: LocalDefId,
493 if self.macro_reachable.insert((module_def_id, defining_mod)) {
494 self.update_macro_reachable_mod(module_def_id, defining_mod);
501 fn update_macro_reachable_mod(&mut self, module_def_id: LocalDefId, defining_mod: LocalDefId) {
502 let module = self.tcx.hir().get_module(module_def_id).0;
503 for item_id in module.item_ids {
504 let def_kind = self.tcx.def_kind(item_id.def_id);
505 let vis = self.tcx.visibility(item_id.def_id);
506 self.update_macro_reachable_def(item_id.def_id, def_kind, vis, defining_mod);
508 if let Some(exports) = self.tcx.module_reexports(module_def_id) {
509 for export in exports {
510 if export.vis.is_accessible_from(defining_mod.to_def_id(), self.tcx) {
511 if let Res::Def(def_kind, def_id) = export.res {
512 if let Some(def_id) = def_id.as_local() {
513 let vis = self.tcx.visibility(def_id.to_def_id());
514 self.update_macro_reachable_def(def_id, def_kind, vis, defining_mod);
522 fn update_macro_reachable_def(
529 let level = Some(AccessLevel::Reachable);
531 self.update(def_id, level);
534 // No type privacy, so can be directly marked as reachable.
535 DefKind::Const | DefKind::Static(_) | DefKind::TraitAlias | DefKind::TyAlias => {
536 if vis.is_accessible_from(module.to_def_id(), self.tcx) {
537 self.update(def_id, level);
541 // Hygiene isn't really implemented for `macro_rules!` macros at the
542 // moment. Accordingly, marking them as reachable is unwise. `macro` macros
543 // have normal hygiene, so we can treat them like other items without type
544 // privacy and mark them reachable.
545 DefKind::Macro(_) => {
546 let item = self.tcx.hir().expect_item(def_id);
547 if let hir::ItemKind::Macro(MacroDef { macro_rules: false, .. }, _) = item.kind {
548 if vis.is_accessible_from(module.to_def_id(), self.tcx) {
549 self.update(def_id, level);
554 // We can't use a module name as the final segment of a path, except
555 // in use statements. Since re-export checking doesn't consider
556 // hygiene these don't need to be marked reachable. The contents of
557 // the module, however may be reachable.
559 if vis.is_accessible_from(module.to_def_id(), self.tcx) {
560 self.update_macro_reachable(def_id, module);
564 DefKind::Struct | DefKind::Union => {
565 // While structs and unions have type privacy, their fields do not.
567 let item = self.tcx.hir().expect_item(def_id);
568 if let hir::ItemKind::Struct(ref struct_def, _)
569 | hir::ItemKind::Union(ref struct_def, _) = item.kind
571 for field in struct_def.fields() {
572 let def_id = self.tcx.hir().local_def_id(field.hir_id);
573 let field_vis = self.tcx.visibility(def_id);
574 if field_vis.is_accessible_from(module.to_def_id(), self.tcx) {
575 self.reach(def_id, level).ty();
579 bug!("item {:?} with DefKind {:?}", item, def_kind);
584 // These have type privacy, so are not reachable unless they're
585 // public, or are not namespaced at all.
588 | DefKind::ConstParam
589 | DefKind::Ctor(_, _)
598 | DefKind::LifetimeParam
599 | DefKind::ExternCrate
601 | DefKind::ForeignMod
603 | DefKind::InlineConst
608 | DefKind::Generator => (),
613 impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> {
614 type NestedFilter = nested_filter::All;
616 /// We want to visit items in the context of their containing
617 /// module and so forth, so supply a crate for doing a deep walk.
618 fn nested_visit_map(&mut self) -> Self::Map {
622 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
623 let item_level = match item.kind {
624 hir::ItemKind::Impl { .. } => {
626 Option::<AccessLevel>::of_impl(item.def_id, self.tcx, &self.access_levels);
627 self.update(item.def_id, impl_level)
629 _ => self.get(item.def_id),
632 // Update levels of nested things.
634 hir::ItemKind::Enum(ref def, _) => {
635 for variant in def.variants {
636 let variant_level = self.update_with_hir_id(variant.id, item_level);
637 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
638 self.update_with_hir_id(ctor_hir_id, item_level);
640 for field in variant.data.fields() {
641 self.update_with_hir_id(field.hir_id, variant_level);
645 hir::ItemKind::Impl(ref impl_) => {
646 for impl_item_ref in impl_.items {
647 if impl_.of_trait.is_some()
648 || self.tcx.visibility(impl_item_ref.id.def_id) == ty::Visibility::Public
650 self.update(impl_item_ref.id.def_id, item_level);
654 hir::ItemKind::Trait(.., trait_item_refs) => {
655 for trait_item_ref in trait_item_refs {
656 self.update(trait_item_ref.id.def_id, item_level);
659 hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => {
660 if let Some(ctor_hir_id) = def.ctor_hir_id() {
661 self.update_with_hir_id(ctor_hir_id, item_level);
663 for field in def.fields() {
664 let def_id = self.tcx.hir().local_def_id(field.hir_id);
665 let vis = self.tcx.visibility(def_id);
667 self.update_with_hir_id(field.hir_id, item_level);
671 hir::ItemKind::Macro(ref macro_def, _) => {
672 self.update_reachability_from_macro(item.def_id, macro_def);
674 hir::ItemKind::ForeignMod { items, .. } => {
675 for foreign_item in items {
676 if self.tcx.visibility(foreign_item.id.def_id) == ty::Visibility::Public {
677 self.update(foreign_item.id.def_id, item_level);
682 hir::ItemKind::OpaqueTy(..)
683 | hir::ItemKind::Use(..)
684 | hir::ItemKind::Static(..)
685 | hir::ItemKind::Const(..)
686 | hir::ItemKind::GlobalAsm(..)
687 | hir::ItemKind::TyAlias(..)
688 | hir::ItemKind::Mod(..)
689 | hir::ItemKind::TraitAlias(..)
690 | hir::ItemKind::Fn(..)
691 | hir::ItemKind::ExternCrate(..) => {}
694 // Mark all items in interfaces of reachable items as reachable.
696 // The interface is empty.
697 hir::ItemKind::Macro(..) | hir::ItemKind::ExternCrate(..) => {}
698 // All nested items are checked by `visit_item`.
699 hir::ItemKind::Mod(..) => {}
700 // Handled in the access level of in rustc_resolve
701 hir::ItemKind::Use(..) => {}
702 // The interface is empty.
703 hir::ItemKind::GlobalAsm(..) => {}
704 hir::ItemKind::OpaqueTy(..) => {
705 // HACK(jynelson): trying to infer the type of `impl trait` breaks `async-std` (and `pub async fn` in general)
706 // Since rustdoc never needs to do codegen and doesn't care about link-time reachability,
707 // mark this as unreachable.
708 // See https://github.com/rust-lang/rust/issues/75100
709 if !self.tcx.sess.opts.actually_rustdoc {
710 // FIXME: This is some serious pessimization intended to workaround deficiencies
711 // in the reachability pass (`middle/reachable.rs`). Types are marked as link-time
712 // reachable if they are returned via `impl Trait`, even from private functions.
714 cmp::max(item_level, Some(AccessLevel::ReachableFromImplTrait));
715 self.reach(item.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.def_id, item_level).generics().predicates().ty();
727 hir::ItemKind::Trait(.., trait_item_refs) => {
728 if item_level.is_some() {
729 self.reach(item.def_id, item_level).generics().predicates();
731 for trait_item_ref in trait_item_refs {
732 let mut reach = self.reach(trait_item_ref.id.def_id, item_level);
733 reach.generics().predicates();
735 if trait_item_ref.kind == AssocItemKind::Type
736 && !trait_item_ref.defaultness.has_value()
745 hir::ItemKind::TraitAlias(..) => {
746 if item_level.is_some() {
747 self.reach(item.def_id, item_level).generics().predicates();
750 // Visit everything except for private impl items.
751 hir::ItemKind::Impl(ref impl_) => {
752 if item_level.is_some() {
753 self.reach(item.def_id, item_level).generics().predicates().ty().trait_ref();
755 for impl_item_ref in impl_.items {
756 let impl_item_level = self.get(impl_item_ref.id.def_id);
757 if impl_item_level.is_some() {
758 self.reach(impl_item_ref.id.def_id, impl_item_level)
767 // Visit everything, but enum variants have their own levels.
768 hir::ItemKind::Enum(ref def, _) => {
769 if item_level.is_some() {
770 self.reach(item.def_id, item_level).generics().predicates();
772 for variant in def.variants {
773 let variant_level = self.get(self.tcx.hir().local_def_id(variant.id));
774 if variant_level.is_some() {
775 for field in variant.data.fields() {
776 self.reach(self.tcx.hir().local_def_id(field.hir_id), variant_level)
779 // Corner case: if the variant is reachable, but its
780 // enum is not, make the enum reachable as well.
781 self.reach(item.def_id, variant_level).ty();
783 if let Some(hir_id) = variant.data.ctor_hir_id() {
784 let ctor_def_id = self.tcx.hir().local_def_id(hir_id);
785 let ctor_level = self.get(ctor_def_id);
786 if ctor_level.is_some() {
787 self.reach(item.def_id, ctor_level).ty();
792 // Visit everything, but foreign items have their own levels.
793 hir::ItemKind::ForeignMod { items, .. } => {
794 for foreign_item in items {
795 let foreign_item_level = self.get(foreign_item.id.def_id);
796 if foreign_item_level.is_some() {
797 self.reach(foreign_item.id.def_id, foreign_item_level)
804 // Visit everything except for private fields.
805 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
806 if item_level.is_some() {
807 self.reach(item.def_id, item_level).generics().predicates();
808 for field in struct_def.fields() {
809 let def_id = self.tcx.hir().local_def_id(field.hir_id);
810 let field_level = self.get(def_id);
811 if field_level.is_some() {
812 self.reach(def_id, field_level).ty();
816 if let Some(hir_id) = struct_def.ctor_hir_id() {
817 let ctor_def_id = self.tcx.hir().local_def_id(hir_id);
818 let ctor_level = self.get(ctor_def_id);
819 if ctor_level.is_some() {
820 self.reach(item.def_id, ctor_level).ty();
826 let orig_level = mem::replace(&mut self.prev_level, item_level);
827 intravisit::walk_item(self, item);
828 self.prev_level = orig_level;
831 fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
832 // Blocks can have public items, for example impls, but they always
833 // start as completely private regardless of publicity of a function,
834 // constant, type, field, etc., in which this block resides.
835 let orig_level = mem::replace(&mut self.prev_level, None);
836 intravisit::walk_block(self, b);
837 self.prev_level = orig_level;
841 impl ReachEverythingInTheInterfaceVisitor<'_, '_> {
842 fn generics(&mut self) -> &mut Self {
843 for param in &self.ev.tcx.generics_of(self.item_def_id).params {
845 GenericParamDefKind::Lifetime => {}
846 GenericParamDefKind::Type { has_default, .. } => {
848 self.visit(self.ev.tcx.type_of(param.def_id));
851 GenericParamDefKind::Const { has_default } => {
852 self.visit(self.ev.tcx.type_of(param.def_id));
854 self.visit(self.ev.tcx.const_param_default(param.def_id));
862 fn predicates(&mut self) -> &mut Self {
863 self.visit_predicates(self.ev.tcx.predicates_of(self.item_def_id));
867 fn ty(&mut self) -> &mut Self {
868 self.visit(self.ev.tcx.type_of(self.item_def_id));
872 fn trait_ref(&mut self) -> &mut Self {
873 if let Some(trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) {
874 self.visit_trait(trait_ref);
880 impl<'tcx> DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
881 fn tcx(&self) -> TyCtxt<'tcx> {
888 _descr: &dyn fmt::Display,
889 ) -> ControlFlow<Self::BreakTy> {
890 if let Some(def_id) = def_id.as_local() {
891 if let (ty::Visibility::Public, _) | (_, Some(AccessLevel::ReachableFromImplTrait)) =
892 (self.tcx().visibility(def_id.to_def_id()), self.access_level)
894 self.ev.update(def_id, self.access_level);
897 ControlFlow::CONTINUE
901 //////////////////////////////////////////////////////////////////////////////////////
902 /// Name privacy visitor, checks privacy and reports violations.
903 /// Most of name privacy checks are performed during the main resolution phase,
904 /// or later in type checking when field accesses and associated items are resolved.
905 /// This pass performs remaining checks for fields in struct expressions and patterns.
906 //////////////////////////////////////////////////////////////////////////////////////
908 struct NamePrivacyVisitor<'tcx> {
910 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
911 current_item: LocalDefId,
914 impl<'tcx> NamePrivacyVisitor<'tcx> {
915 /// Gets the type-checking results for the current body.
916 /// As this will ICE if called outside bodies, only call when working with
917 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
919 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
920 self.maybe_typeck_results
921 .expect("`NamePrivacyVisitor::typeck_results` called outside of body")
924 // Checks that a field in a struct constructor (expression or pattern) is accessible.
927 use_ctxt: Span, // syntax context of the field name at the use site
928 span: Span, // span of the field pattern, e.g., `x: 0`
929 def: ty::AdtDef<'tcx>, // definition of the struct or enum
930 field: &'tcx ty::FieldDef,
931 in_update_syntax: bool,
937 // definition of the field
938 let ident = Ident::new(kw::Empty, use_ctxt);
939 let hir_id = self.tcx.hir().local_def_id_to_hir_id(self.current_item);
940 let def_id = self.tcx.adjust_ident_and_get_scope(ident, def.did(), hir_id).1;
941 if !field.vis.is_accessible_from(def_id, self.tcx) {
942 self.tcx.sess.emit_err(FieldIsPrivate {
944 field_name: field.name,
945 variant_descr: def.variant_descr(),
946 def_path_str: self.tcx.def_path_str(def.did()),
947 label: if in_update_syntax {
948 FieldIsPrivateLabel::IsUpdateSyntax { span, field_name: field.name }
950 FieldIsPrivateLabel::Other { span }
957 impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> {
958 type NestedFilter = nested_filter::All;
960 /// We want to visit items in the context of their containing
961 /// module and so forth, so supply a crate for doing a deep walk.
962 fn nested_visit_map(&mut self) -> Self::Map {
966 fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) {
967 // Don't visit nested modules, since we run a separate visitor walk
968 // for each module in `privacy_access_levels`
971 fn visit_nested_body(&mut self, body: hir::BodyId) {
972 let old_maybe_typeck_results =
973 self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
974 let body = self.tcx.hir().body(body);
975 self.visit_body(body);
976 self.maybe_typeck_results = old_maybe_typeck_results;
979 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
980 let orig_current_item = mem::replace(&mut self.current_item, item.def_id);
981 intravisit::walk_item(self, item);
982 self.current_item = orig_current_item;
985 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
986 if let hir::ExprKind::Struct(qpath, fields, ref base) = expr.kind {
987 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
988 let adt = self.typeck_results().expr_ty(expr).ty_adt_def().unwrap();
989 let variant = adt.variant_of_res(res);
990 if let Some(base) = *base {
991 // If the expression uses FRU we need to make sure all the unmentioned fields
992 // are checked for privacy (RFC 736). Rather than computing the set of
993 // unmentioned fields, just check them all.
994 for (vf_index, variant_field) in variant.fields.iter().enumerate() {
995 let field = fields.iter().find(|f| {
996 self.tcx.field_index(f.hir_id, self.typeck_results()) == vf_index
998 let (use_ctxt, span) = match field {
999 Some(field) => (field.ident.span, field.span),
1000 None => (base.span, base.span),
1002 self.check_field(use_ctxt, span, adt, variant_field, true);
1005 for field in fields {
1006 let use_ctxt = field.ident.span;
1007 let index = self.tcx.field_index(field.hir_id, self.typeck_results());
1008 self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false);
1013 intravisit::walk_expr(self, expr);
1016 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
1017 if let PatKind::Struct(ref qpath, fields, _) = pat.kind {
1018 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
1019 let adt = self.typeck_results().pat_ty(pat).ty_adt_def().unwrap();
1020 let variant = adt.variant_of_res(res);
1021 for field in fields {
1022 let use_ctxt = field.ident.span;
1023 let index = self.tcx.field_index(field.hir_id, self.typeck_results());
1024 self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false);
1028 intravisit::walk_pat(self, pat);
1032 ////////////////////////////////////////////////////////////////////////////////////////////
1033 /// Type privacy visitor, checks types for privacy and reports violations.
1034 /// Both explicitly written types and inferred types of expressions and patterns are checked.
1035 /// Checks are performed on "semantic" types regardless of names and their hygiene.
1036 ////////////////////////////////////////////////////////////////////////////////////////////
1038 struct TypePrivacyVisitor<'tcx> {
1040 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
1041 current_item: LocalDefId,
1045 impl<'tcx> TypePrivacyVisitor<'tcx> {
1046 /// Gets the type-checking results for the current body.
1047 /// As this will ICE if called outside bodies, only call when working with
1048 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
1050 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
1051 self.maybe_typeck_results
1052 .expect("`TypePrivacyVisitor::typeck_results` called outside of body")
1055 fn item_is_accessible(&self, did: DefId) -> bool {
1056 self.tcx.visibility(did).is_accessible_from(self.current_item.to_def_id(), self.tcx)
1059 // Take node-id of an expression or pattern and check its type for privacy.
1060 fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
1062 let typeck_results = self.typeck_results();
1063 let result: ControlFlow<()> = try {
1064 self.visit(typeck_results.node_type(id))?;
1065 self.visit(typeck_results.node_substs(id))?;
1066 if let Some(adjustments) = typeck_results.adjustments().get(id) {
1067 adjustments.iter().try_for_each(|adjustment| self.visit(adjustment.target))?;
1073 fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1074 let is_error = !self.item_is_accessible(def_id);
1076 self.tcx.sess.emit_err(ItemIsPrivate {
1079 descr: descr.to_string(),
1086 impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> {
1087 type NestedFilter = nested_filter::All;
1089 /// We want to visit items in the context of their containing
1090 /// module and so forth, so supply a crate for doing a deep walk.
1091 fn nested_visit_map(&mut self) -> Self::Map {
1095 fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) {
1096 // Don't visit nested modules, since we run a separate visitor walk
1097 // for each module in `privacy_access_levels`
1100 fn visit_nested_body(&mut self, body: hir::BodyId) {
1101 let old_maybe_typeck_results =
1102 self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
1103 let body = self.tcx.hir().body(body);
1104 self.visit_body(body);
1105 self.maybe_typeck_results = old_maybe_typeck_results;
1108 fn visit_generic_arg(&mut self, generic_arg: &'tcx hir::GenericArg<'tcx>) {
1110 hir::GenericArg::Type(t) => self.visit_ty(t),
1111 hir::GenericArg::Infer(inf) => self.visit_infer(inf),
1112 hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {}
1116 fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) {
1117 self.span = hir_ty.span;
1118 if let Some(typeck_results) = self.maybe_typeck_results {
1120 if self.visit(typeck_results.node_type(hir_ty.hir_id)).is_break() {
1124 // Types in signatures.
1125 // FIXME: This is very ineffective. Ideally each HIR type should be converted
1126 // into a semantic type only once and the result should be cached somehow.
1127 if self.visit(rustc_typeck::hir_ty_to_ty(self.tcx, hir_ty)).is_break() {
1132 intravisit::walk_ty(self, hir_ty);
1135 fn visit_infer(&mut self, inf: &'tcx hir::InferArg) {
1136 self.span = inf.span;
1137 if let Some(typeck_results) = self.maybe_typeck_results {
1138 if let Some(ty) = typeck_results.node_type_opt(inf.hir_id) {
1139 if self.visit(ty).is_break() {
1143 // We don't do anything for const infers here.
1146 bug!("visit_infer without typeck_results");
1148 intravisit::walk_inf(self, inf);
1151 fn visit_trait_ref(&mut self, trait_ref: &'tcx hir::TraitRef<'tcx>) {
1152 self.span = trait_ref.path.span;
1153 if self.maybe_typeck_results.is_none() {
1154 // Avoid calling `hir_trait_to_predicates` in bodies, it will ICE.
1155 // The traits' privacy in bodies is already checked as a part of trait object types.
1156 let bounds = rustc_typeck::hir_trait_to_predicates(
1159 // NOTE: This isn't really right, but the actual type doesn't matter here. It's
1160 // just required by `ty::TraitRef`.
1161 self.tcx.types.never,
1164 for (trait_predicate, _, _) in bounds.trait_bounds {
1165 if self.visit_trait(trait_predicate.skip_binder()).is_break() {
1170 for (poly_predicate, _) in bounds.projection_bounds {
1171 let pred = poly_predicate.skip_binder();
1172 let poly_pred_term = self.visit(pred.term);
1173 if poly_pred_term.is_break()
1174 || self.visit_projection_ty(pred.projection_ty).is_break()
1181 intravisit::walk_trait_ref(self, trait_ref);
1184 // Check types of expressions
1185 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1186 if self.check_expr_pat_type(expr.hir_id, expr.span) {
1187 // Do not check nested expressions if the error already happened.
1191 hir::ExprKind::Assign(_, rhs, _) | hir::ExprKind::Match(rhs, ..) => {
1192 // Do not report duplicate errors for `x = y` and `match x { ... }`.
1193 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
1197 hir::ExprKind::MethodCall(segment, ..) => {
1198 // Method calls have to be checked specially.
1199 self.span = segment.ident.span;
1200 if let Some(def_id) = self.typeck_results().type_dependent_def_id(expr.hir_id) {
1201 if self.visit(self.tcx.type_of(def_id)).is_break() {
1207 .delay_span_bug(expr.span, "no type-dependent def for method call");
1213 intravisit::walk_expr(self, expr);
1216 // Prohibit access to associated items with insufficient nominal visibility.
1218 // Additionally, until better reachability analysis for macros 2.0 is available,
1219 // we prohibit access to private statics from other crates, this allows to give
1220 // more code internal visibility at link time. (Access to private functions
1221 // is already prohibited by type privacy for function types.)
1222 fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) {
1223 let def = match qpath {
1224 hir::QPath::Resolved(_, path) => match path.res {
1225 Res::Def(kind, def_id) => Some((kind, def_id)),
1228 hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
1229 .maybe_typeck_results
1230 .and_then(|typeck_results| typeck_results.type_dependent_def(id)),
1232 let def = def.filter(|(kind, _)| {
1235 DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static(_)
1238 if let Some((kind, def_id)) = def {
1239 let is_local_static =
1240 if let DefKind::Static(_) = kind { def_id.is_local() } else { false };
1241 if !self.item_is_accessible(def_id) && !is_local_static {
1242 let sess = self.tcx.sess;
1243 let sm = sess.source_map();
1244 let name = match qpath {
1245 hir::QPath::Resolved(..) | hir::QPath::LangItem(..) => {
1246 sm.span_to_snippet(qpath.span()).ok()
1248 hir::QPath::TypeRelative(_, segment) => Some(segment.ident.to_string()),
1250 let kind = kind.descr(def_id);
1251 let _ = match name {
1252 Some(name) => sess.emit_err(ItemIsPrivate { span, kind, descr: name }),
1253 None => sess.emit_err(UnnamedItemIsPrivate { span, kind }),
1259 intravisit::walk_qpath(self, qpath, id, span);
1262 // Check types of patterns.
1263 fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) {
1264 if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
1265 // Do not check nested patterns if the error already happened.
1269 intravisit::walk_pat(self, pattern);
1272 fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) {
1273 if let Some(init) = local.init {
1274 if self.check_expr_pat_type(init.hir_id, init.span) {
1275 // Do not report duplicate errors for `let x = y`.
1280 intravisit::walk_local(self, local);
1283 // Check types in item interfaces.
1284 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1285 let orig_current_item = mem::replace(&mut self.current_item, item.def_id);
1286 let old_maybe_typeck_results = self.maybe_typeck_results.take();
1287 intravisit::walk_item(self, item);
1288 self.maybe_typeck_results = old_maybe_typeck_results;
1289 self.current_item = orig_current_item;
1293 impl<'tcx> DefIdVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1294 fn tcx(&self) -> TyCtxt<'tcx> {
1301 descr: &dyn fmt::Display,
1302 ) -> ControlFlow<Self::BreakTy> {
1303 if self.check_def_id(def_id, kind, descr) {
1306 ControlFlow::CONTINUE
1311 ///////////////////////////////////////////////////////////////////////////////
1312 /// Obsolete visitors for checking for private items in public interfaces.
1313 /// These visitors are supposed to be kept in frozen state and produce an
1314 /// "old error node set". For backward compatibility the new visitor reports
1315 /// warnings instead of hard errors when the erroneous node is not in this old set.
1316 ///////////////////////////////////////////////////////////////////////////////
1318 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1320 access_levels: &'a AccessLevels,
1322 // Set of errors produced by this obsolete visitor.
1323 old_error_set: HirIdSet,
1326 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1327 inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
1328 /// Whether the type refers to private types.
1329 contains_private: bool,
1330 /// Whether we've recurred at all (i.e., if we're pointing at the
1331 /// first type on which `visit_ty` was called).
1332 at_outer_type: bool,
1333 /// Whether that first type is a public path.
1334 outer_type_is_public_path: bool,
1337 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1338 fn path_is_private_type(&self, path: &hir::Path<'_>) -> bool {
1339 let did = match path.res {
1340 Res::PrimTy(..) | Res::SelfTy { .. } | Res::Err => return false,
1341 res => res.def_id(),
1344 // A path can only be private if:
1345 // it's in this crate...
1346 if let Some(did) = did.as_local() {
1347 // .. and it corresponds to a private type in the AST (this returns
1348 // `None` for type parameters).
1349 match self.tcx.hir().find(self.tcx.hir().local_def_id_to_hir_id(did)) {
1350 Some(Node::Item(_)) => !self.tcx.visibility(did).is_public(),
1351 Some(_) | None => false,
1358 fn trait_is_public(&self, trait_id: LocalDefId) -> bool {
1359 // FIXME: this would preferably be using `exported_items`, but all
1360 // traits are exported currently (see `EmbargoVisitor.exported_trait`).
1361 self.access_levels.is_public(trait_id)
1364 fn check_generic_bound(&mut self, bound: &hir::GenericBound<'_>) {
1365 if let hir::GenericBound::Trait(ref trait_ref, _) = *bound {
1366 if self.path_is_private_type(trait_ref.trait_ref.path) {
1367 self.old_error_set.insert(trait_ref.trait_ref.hir_ref_id);
1372 fn item_is_public(&self, def_id: LocalDefId) -> bool {
1373 self.access_levels.is_reachable(def_id) || self.tcx.visibility(def_id).is_public()
1377 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1378 fn visit_generic_arg(&mut self, generic_arg: &'v hir::GenericArg<'v>) {
1380 hir::GenericArg::Type(t) => self.visit_ty(t),
1381 hir::GenericArg::Infer(inf) => self.visit_ty(&inf.to_ty()),
1382 hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {}
1386 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
1387 if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = ty.kind {
1388 if self.inner.path_is_private_type(path) {
1389 self.contains_private = true;
1390 // Found what we're looking for, so let's stop working.
1394 if let hir::TyKind::Path(_) = ty.kind {
1395 if self.at_outer_type {
1396 self.outer_type_is_public_path = true;
1399 self.at_outer_type = false;
1400 intravisit::walk_ty(self, ty)
1403 // Don't want to recurse into `[, .. expr]`.
1404 fn visit_expr(&mut self, _: &hir::Expr<'_>) {}
1407 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1408 type NestedFilter = nested_filter::All;
1410 /// We want to visit items in the context of their containing
1411 /// module and so forth, so supply a crate for doing a deep walk.
1412 fn nested_visit_map(&mut self) -> Self::Map {
1416 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1418 // Contents of a private mod can be re-exported, so we need
1419 // to check internals.
1420 hir::ItemKind::Mod(_) => {}
1422 // An `extern {}` doesn't introduce a new privacy
1423 // namespace (the contents have their own privacies).
1424 hir::ItemKind::ForeignMod { .. } => {}
1426 hir::ItemKind::Trait(.., bounds, _) => {
1427 if !self.trait_is_public(item.def_id) {
1431 for bound in bounds.iter() {
1432 self.check_generic_bound(bound)
1436 // Impls need some special handling to try to offer useful
1437 // error messages without (too many) false positives
1438 // (i.e., we could just return here to not check them at
1439 // all, or some worse estimation of whether an impl is
1440 // publicly visible).
1441 hir::ItemKind::Impl(ref impl_) => {
1442 // `impl [... for] Private` is never visible.
1443 let self_contains_private;
1444 // `impl [... for] Public<...>`, but not `impl [... for]
1445 // Vec<Public>` or `(Public,)`, etc.
1446 let self_is_public_path;
1448 // Check the properties of the `Self` type:
1450 let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
1452 contains_private: false,
1453 at_outer_type: true,
1454 outer_type_is_public_path: false,
1456 visitor.visit_ty(impl_.self_ty);
1457 self_contains_private = visitor.contains_private;
1458 self_is_public_path = visitor.outer_type_is_public_path;
1461 // Miscellaneous info about the impl:
1463 // `true` iff this is `impl Private for ...`.
1464 let not_private_trait = impl_.of_trait.as_ref().map_or(
1465 true, // no trait counts as public trait
1467 if let Some(def_id) = tr.path.res.def_id().as_local() {
1468 self.trait_is_public(def_id)
1470 true // external traits must be public
1475 // `true` iff this is a trait impl or at least one method is public.
1477 // `impl Public { $( fn ...() {} )* }` is not visible.
1479 // This is required over just using the methods' privacy
1480 // directly because we might have `impl<T: Foo<Private>> ...`,
1481 // and we shouldn't warn about the generics if all the methods
1482 // are private (because `T` won't be visible externally).
1483 let trait_or_some_public_method = impl_.of_trait.is_some()
1484 || impl_.items.iter().any(|impl_item_ref| {
1485 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1486 match impl_item.kind {
1487 hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) => {
1488 self.access_levels.is_reachable(impl_item_ref.id.def_id)
1490 hir::ImplItemKind::TyAlias(_) => false,
1494 if !self_contains_private && not_private_trait && trait_or_some_public_method {
1495 intravisit::walk_generics(self, &impl_.generics);
1497 match impl_.of_trait {
1499 for impl_item_ref in impl_.items {
1500 // This is where we choose whether to walk down
1501 // further into the impl to check its items. We
1502 // should only walk into public items so that we
1503 // don't erroneously report errors for private
1504 // types in private items.
1505 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1506 match impl_item.kind {
1507 hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..)
1508 if self.item_is_public(impl_item.def_id) =>
1510 intravisit::walk_impl_item(self, impl_item)
1512 hir::ImplItemKind::TyAlias(..) => {
1513 intravisit::walk_impl_item(self, impl_item)
1520 // Any private types in a trait impl fall into three
1522 // 1. mentioned in the trait definition
1523 // 2. mentioned in the type params/generics
1524 // 3. mentioned in the associated types of the impl
1526 // Those in 1. can only occur if the trait is in
1527 // this crate and will have been warned about on the
1528 // trait definition (there's no need to warn twice
1529 // so we don't check the methods).
1531 // Those in 2. are warned via walk_generics and this
1533 intravisit::walk_path(self, tr.path);
1535 // Those in 3. are warned with this call.
1536 for impl_item_ref in impl_.items {
1537 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1538 if let hir::ImplItemKind::TyAlias(ty) = impl_item.kind {
1544 } else if impl_.of_trait.is_none() && self_is_public_path {
1545 // `impl Public<Private> { ... }`. Any public static
1546 // methods will be visible as `Public::foo`.
1547 let mut found_pub_static = false;
1548 for impl_item_ref in impl_.items {
1549 if self.access_levels.is_reachable(impl_item_ref.id.def_id)
1550 || self.tcx.visibility(impl_item_ref.id.def_id)
1551 == ty::Visibility::Public
1553 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1554 match impl_item_ref.kind {
1555 AssocItemKind::Const => {
1556 found_pub_static = true;
1557 intravisit::walk_impl_item(self, impl_item);
1559 AssocItemKind::Fn { has_self: false } => {
1560 found_pub_static = true;
1561 intravisit::walk_impl_item(self, impl_item);
1567 if found_pub_static {
1568 intravisit::walk_generics(self, &impl_.generics)
1574 // `type ... = ...;` can contain private types, because
1575 // we're introducing a new name.
1576 hir::ItemKind::TyAlias(..) => return,
1578 // Not at all public, so we don't care.
1579 _ if !self.item_is_public(item.def_id) => {
1586 // We've carefully constructed it so that if we're here, then
1587 // any `visit_ty`'s will be called on things that are in
1588 // public signatures, i.e., things that we're interested in for
1590 intravisit::walk_item(self, item);
1593 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1594 for predicate in generics.predicates {
1596 hir::WherePredicate::BoundPredicate(bound_pred) => {
1597 for bound in bound_pred.bounds.iter() {
1598 self.check_generic_bound(bound)
1601 hir::WherePredicate::RegionPredicate(_) => {}
1602 hir::WherePredicate::EqPredicate(eq_pred) => {
1603 self.visit_ty(eq_pred.rhs_ty);
1609 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
1610 if self.access_levels.is_reachable(item.def_id) {
1611 intravisit::walk_foreign_item(self, item)
1615 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
1616 if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = t.kind {
1617 if self.path_is_private_type(path) {
1618 self.old_error_set.insert(t.hir_id);
1621 intravisit::walk_ty(self, t)
1626 v: &'tcx hir::Variant<'tcx>,
1627 g: &'tcx hir::Generics<'tcx>,
1628 item_id: hir::HirId,
1630 if self.access_levels.is_reachable(self.tcx.hir().local_def_id(v.id)) {
1631 self.in_variant = true;
1632 intravisit::walk_variant(self, v, g, item_id);
1633 self.in_variant = false;
1637 fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) {
1638 let def_id = self.tcx.hir().local_def_id(s.hir_id);
1639 let vis = self.tcx.visibility(def_id);
1640 if vis.is_public() || self.in_variant {
1641 intravisit::walk_field_def(self, s);
1645 // We don't need to introspect into these at all: an
1646 // expression/block context can't possibly contain exported things.
1647 // (Making them no-ops stops us from traversing the whole AST without
1648 // having to be super careful about our `walk_...` calls above.)
1649 fn visit_block(&mut self, _: &'tcx hir::Block<'tcx>) {}
1650 fn visit_expr(&mut self, _: &'tcx hir::Expr<'tcx>) {}
1653 ///////////////////////////////////////////////////////////////////////////////
1654 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1655 /// finds any private components in it.
1656 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1657 /// and traits in public interfaces.
1658 ///////////////////////////////////////////////////////////////////////////////
1660 struct SearchInterfaceForPrivateItemsVisitor<'tcx> {
1662 item_def_id: LocalDefId,
1663 /// The visitor checks that each component type is at least this visible.
1664 required_visibility: ty::Visibility,
1665 has_old_errors: bool,
1669 impl SearchInterfaceForPrivateItemsVisitor<'_> {
1670 fn generics(&mut self) -> &mut Self {
1671 for param in &self.tcx.generics_of(self.item_def_id).params {
1673 GenericParamDefKind::Lifetime => {}
1674 GenericParamDefKind::Type { has_default, .. } => {
1676 self.visit(self.tcx.type_of(param.def_id));
1679 // FIXME(generic_const_exprs): May want to look inside const here
1680 GenericParamDefKind::Const { .. } => {
1681 self.visit(self.tcx.type_of(param.def_id));
1688 fn predicates(&mut self) -> &mut Self {
1689 // N.B., we use `explicit_predicates_of` and not `predicates_of`
1690 // because we don't want to report privacy errors due to where
1691 // clauses that the compiler inferred. We only want to
1692 // consider the ones that the user wrote. This is important
1693 // for the inferred outlives rules; see
1694 // `src/test/ui/rfc-2093-infer-outlives/privacy.rs`.
1695 self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id));
1699 fn bounds(&mut self) -> &mut Self {
1700 self.visit_predicates(ty::GenericPredicates {
1702 predicates: self.tcx.explicit_item_bounds(self.item_def_id),
1707 fn ty(&mut self) -> &mut Self {
1708 self.visit(self.tcx.type_of(self.item_def_id));
1712 fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1713 if self.leaks_private_dep(def_id) {
1714 self.tcx.struct_span_lint_hir(
1715 lint::builtin::EXPORTED_PRIVATE_DEPENDENCIES,
1716 self.tcx.hir().local_def_id_to_hir_id(self.item_def_id),
1717 self.tcx.def_span(self.item_def_id.to_def_id()),
1719 lint.build(&format!(
1720 "{} `{}` from private dependency '{}' in public \
1724 self.tcx.crate_name(def_id.krate)
1731 let hir_id = match def_id.as_local() {
1732 Some(def_id) => self.tcx.hir().local_def_id_to_hir_id(def_id),
1733 None => return false,
1736 let vis = self.tcx.visibility(def_id);
1737 if !vis.is_at_least(self.required_visibility, self.tcx) {
1738 let vis_descr = match vis {
1739 ty::Visibility::Public => "public",
1740 ty::Visibility::Invisible => "private",
1741 ty::Visibility::Restricted(vis_def_id) => {
1742 if vis_def_id == self.tcx.parent_module(hir_id).to_def_id() {
1744 } else if vis_def_id.is_top_level_module() {
1751 let make_msg = || format!("{} {} `{}` in public interface", vis_descr, kind, descr);
1752 let span = self.tcx.def_span(self.item_def_id.to_def_id());
1753 if self.has_old_errors
1755 || self.tcx.resolutions(()).has_pub_restricted
1757 let mut err = if kind == "trait" {
1758 struct_span_err!(self.tcx.sess, span, E0445, "{}", make_msg())
1760 struct_span_err!(self.tcx.sess, span, E0446, "{}", make_msg())
1763 self.tcx.sess.source_map().guess_head_span(self.tcx.def_span(def_id));
1764 err.span_label(span, format!("can't leak {} {}", vis_descr, kind));
1765 err.span_label(vis_span, format!("`{}` declared as {}", descr, vis_descr));
1768 let err_code = if kind == "trait" { "E0445" } else { "E0446" };
1769 self.tcx.struct_span_lint_hir(
1770 lint::builtin::PRIVATE_IN_PUBLIC,
1774 lint.build(&format!("{} (error {})", make_msg(), err_code)).emit();
1783 /// An item is 'leaked' from a private dependency if all
1784 /// of the following are true:
1785 /// 1. It's contained within a public type
1786 /// 2. It comes from a private crate
1787 fn leaks_private_dep(&self, item_id: DefId) -> bool {
1788 let ret = self.required_visibility.is_public() && self.tcx.is_private_dep(item_id.krate);
1790 tracing::debug!("leaks_private_dep(item_id={:?})={}", item_id, ret);
1795 impl<'tcx> DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> {
1796 fn tcx(&self) -> TyCtxt<'tcx> {
1803 descr: &dyn fmt::Display,
1804 ) -> ControlFlow<Self::BreakTy> {
1805 if self.check_def_id(def_id, kind, descr) {
1808 ControlFlow::CONTINUE
1813 struct PrivateItemsInPublicInterfacesChecker<'tcx> {
1815 old_error_set_ancestry: LocalDefIdSet,
1818 impl<'tcx> PrivateItemsInPublicInterfacesChecker<'tcx> {
1822 required_visibility: ty::Visibility,
1823 ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> {
1824 SearchInterfaceForPrivateItemsVisitor {
1826 item_def_id: def_id,
1827 required_visibility,
1828 has_old_errors: self.old_error_set_ancestry.contains(&def_id),
1833 fn check_assoc_item(
1836 assoc_item_kind: AssocItemKind,
1837 defaultness: hir::Defaultness,
1838 vis: ty::Visibility,
1840 let mut check = self.check(def_id, vis);
1842 let (check_ty, is_assoc_ty) = match assoc_item_kind {
1843 AssocItemKind::Const | AssocItemKind::Fn { .. } => (true, false),
1844 AssocItemKind::Type => (defaultness.has_value(), true),
1846 check.in_assoc_ty = is_assoc_ty;
1847 check.generics().predicates();
1853 pub fn check_item(&mut self, id: ItemId) {
1855 let item_visibility = tcx.visibility(id.def_id);
1856 let def_kind = tcx.def_kind(id.def_id);
1859 DefKind::Const | DefKind::Static(_) | DefKind::Fn | DefKind::TyAlias => {
1860 self.check(id.def_id, item_visibility).generics().predicates().ty();
1862 DefKind::OpaqueTy => {
1863 // `ty()` for opaque types is the underlying type,
1864 // it's not a part of interface, so we skip it.
1865 self.check(id.def_id, item_visibility).generics().bounds();
1868 let item = tcx.hir().item(id);
1869 if let hir::ItemKind::Trait(.., trait_item_refs) = item.kind {
1870 self.check(item.def_id, item_visibility).generics().predicates();
1872 for trait_item_ref in trait_item_refs {
1873 self.check_assoc_item(
1874 trait_item_ref.id.def_id,
1875 trait_item_ref.kind,
1876 trait_item_ref.defaultness,
1880 if let AssocItemKind::Type = trait_item_ref.kind {
1881 self.check(trait_item_ref.id.def_id, item_visibility).bounds();
1886 DefKind::TraitAlias => {
1887 self.check(id.def_id, item_visibility).generics().predicates();
1890 let item = tcx.hir().item(id);
1891 if let hir::ItemKind::Enum(ref def, _) = item.kind {
1892 self.check(item.def_id, item_visibility).generics().predicates();
1894 for variant in def.variants {
1895 for field in variant.data.fields() {
1896 self.check(self.tcx.hir().local_def_id(field.hir_id), item_visibility)
1902 // Subitems of foreign modules have their own publicity.
1903 DefKind::ForeignMod => {
1904 let item = tcx.hir().item(id);
1905 if let hir::ItemKind::ForeignMod { items, .. } = item.kind {
1906 for foreign_item in items {
1907 let vis = tcx.visibility(foreign_item.id.def_id);
1908 self.check(foreign_item.id.def_id, vis).generics().predicates().ty();
1912 // Subitems of structs and unions have their own publicity.
1913 DefKind::Struct | DefKind::Union => {
1914 let item = tcx.hir().item(id);
1915 if let hir::ItemKind::Struct(ref struct_def, _)
1916 | hir::ItemKind::Union(ref struct_def, _) = item.kind
1918 self.check(item.def_id, item_visibility).generics().predicates();
1920 for field in struct_def.fields() {
1921 let def_id = tcx.hir().local_def_id(field.hir_id);
1922 let field_visibility = tcx.visibility(def_id);
1923 self.check(def_id, min(item_visibility, field_visibility, tcx)).ty();
1927 // An inherent impl is public when its type is public
1928 // Subitems of inherent impls have their own publicity.
1929 // A trait impl is public when both its type and its trait are public
1930 // Subitems of trait impls have inherited publicity.
1932 let item = tcx.hir().item(id);
1933 if let hir::ItemKind::Impl(ref impl_) = item.kind {
1934 let impl_vis = ty::Visibility::of_impl(item.def_id, tcx, &Default::default());
1935 // check that private components do not appear in the generics or predicates of inherent impls
1936 // this check is intentionally NOT performed for impls of traits, per #90586
1937 if impl_.of_trait.is_none() {
1938 self.check(item.def_id, impl_vis).generics().predicates();
1940 for impl_item_ref in impl_.items {
1941 let impl_item_vis = if impl_.of_trait.is_none() {
1942 min(tcx.visibility(impl_item_ref.id.def_id), impl_vis, tcx)
1946 self.check_assoc_item(
1947 impl_item_ref.id.def_id,
1949 impl_item_ref.defaultness,
1960 pub fn provide(providers: &mut Providers) {
1961 *providers = Providers {
1963 privacy_access_levels,
1964 check_private_in_public,
1970 fn visibility(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Visibility {
1971 let def_id = def_id.expect_local();
1972 match tcx.resolutions(()).visibilities.get(&def_id) {
1975 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1976 match tcx.hir().get(hir_id) {
1977 // Unique types created for closures participate in type privacy checking.
1978 // They have visibilities inherited from the module they are defined in.
1979 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure{..}, .. })
1980 // - AST lowering creates dummy `use` items which don't
1981 // get their entries in the resolver's visibility table.
1982 // - AST lowering also creates opaque type items with inherited visibilities.
1983 // Visibility on them should have no effect, but to avoid the visibility
1984 // query failing on some items, we provide it for opaque types as well.
1985 | Node::Item(hir::Item {
1986 kind: hir::ItemKind::Use(_, hir::UseKind::ListStem) | hir::ItemKind::OpaqueTy(..),
1988 }) => ty::Visibility::Restricted(tcx.parent_module(hir_id).to_def_id()),
1989 // Visibilities of trait impl items are inherited from their traits
1990 // and are not filled in resolve.
1991 Node::ImplItem(impl_item) => {
1992 match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(hir_id)) {
1993 Node::Item(hir::Item {
1994 kind: hir::ItemKind::Impl(hir::Impl { of_trait: Some(tr), .. }),
1996 }) => tr.path.res.opt_def_id().map_or_else(
1998 tcx.sess.delay_span_bug(tr.path.span, "trait without a def-id");
1999 ty::Visibility::Public
2001 |def_id| tcx.visibility(def_id),
2003 _ => span_bug!(impl_item.span, "the parent is not a trait impl"),
2007 tcx.def_span(def_id),
2008 "visibility table unexpectedly missing a def-id: {:?}",
2016 fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
2017 // Check privacy of names not checked in previous compilation stages.
2019 NamePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id };
2020 let (module, span, hir_id) = tcx.hir().get_module(module_def_id);
2022 intravisit::walk_mod(&mut visitor, module, hir_id);
2024 // Check privacy of explicitly written types and traits as well as
2025 // inferred types of expressions and patterns.
2027 TypePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id, span };
2028 intravisit::walk_mod(&mut visitor, module, hir_id);
2031 fn privacy_access_levels(tcx: TyCtxt<'_>, (): ()) -> &AccessLevels {
2032 // Build up a set of all exported items in the AST. This is a set of all
2033 // items which are reachable from external crates based on visibility.
2034 let mut visitor = EmbargoVisitor {
2036 access_levels: tcx.resolutions(()).access_levels.clone(),
2037 macro_reachable: Default::default(),
2038 prev_level: Some(AccessLevel::Public),
2043 tcx.hir().walk_toplevel_module(&mut visitor);
2044 if visitor.changed {
2045 visitor.changed = false;
2051 tcx.arena.alloc(visitor.access_levels)
2054 fn check_private_in_public(tcx: TyCtxt<'_>, (): ()) {
2055 let access_levels = tcx.privacy_access_levels(());
2057 let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
2061 old_error_set: Default::default(),
2063 tcx.hir().walk_toplevel_module(&mut visitor);
2065 let mut old_error_set_ancestry = HirIdSet::default();
2066 for mut id in visitor.old_error_set.iter().copied() {
2068 if !old_error_set_ancestry.insert(id) {
2071 let parent = tcx.hir().get_parent_node(id);
2079 // Check for private types and traits in public interfaces.
2080 let mut checker = PrivateItemsInPublicInterfacesChecker {
2082 // Only definition IDs are ever searched in `old_error_set_ancestry`,
2083 // so we can filter away all non-definition IDs at this point.
2084 old_error_set_ancestry: old_error_set_ancestry
2086 .filter_map(|hir_id| tcx.hir().opt_local_def_id(hir_id))
2090 for id in tcx.hir().items() {
2091 checker.check_item(id);