1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
2 #![feature(in_band_lifetimes)]
4 #![feature(or_patterns)]
5 #![recursion_limit = "256"]
7 use rustc_attr as attr;
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_errors::struct_span_err;
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
13 use rustc_hir::intravisit::{self, DeepVisitor, NestedVisitorMap, Visitor};
14 use rustc_hir::{AssocItemKind, HirIdSet, Node, PatKind};
15 use rustc_middle::bug;
16 use rustc_middle::hir::map::Map;
17 use rustc_middle::middle::privacy::{AccessLevel, AccessLevels};
18 use rustc_middle::ty::fold::TypeVisitor;
19 use rustc_middle::ty::query::Providers;
20 use rustc_middle::ty::subst::InternalSubsts;
21 use rustc_middle::ty::{self, GenericParamDefKind, TraitRef, Ty, TyCtxt, TypeFoldable};
22 use rustc_session::lint;
23 use rustc_span::hygiene::Transparency;
24 use rustc_span::symbol::{kw, sym, Ident};
27 use std::marker::PhantomData;
28 use std::{cmp, fmt, mem};
30 ////////////////////////////////////////////////////////////////////////////////
31 /// Generic infrastructure used to implement specific visitors below.
32 ////////////////////////////////////////////////////////////////////////////////
34 /// Implemented to visit all `DefId`s in a type.
35 /// Visiting `DefId`s is useful because visibilities and reachabilities are attached to them.
36 /// The idea is to visit "all components of a type", as documented in
37 /// https://github.com/rust-lang/rfcs/blob/master/text/2145-type-privacy.md#how-to-determine-visibility-of-a-type.
38 /// The default type visitor (`TypeVisitor`) does most of the job, but it has some shortcomings.
39 /// First, it doesn't have overridable `fn visit_trait_ref`, so we have to catch trait `DefId`s
40 /// manually. Second, it doesn't visit some type components like signatures of fn types, or traits
41 /// in `impl Trait`, see individual comments in `DefIdVisitorSkeleton::visit_ty`.
42 trait DefIdVisitor<'tcx> {
43 fn tcx(&self) -> TyCtxt<'tcx>;
44 fn shallow(&self) -> bool {
47 fn skip_assoc_tys(&self) -> bool {
50 fn visit_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool;
52 /// Not overridden, but used to actually visit types and traits.
53 fn skeleton(&mut self) -> DefIdVisitorSkeleton<'_, 'tcx, Self> {
54 DefIdVisitorSkeleton {
56 visited_opaque_tys: Default::default(),
57 dummy: Default::default(),
60 fn visit(&mut self, ty_fragment: impl TypeFoldable<'tcx>) -> bool {
61 ty_fragment.visit_with(&mut self.skeleton())
63 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> bool {
64 self.skeleton().visit_trait(trait_ref)
66 fn visit_predicates(&mut self, predicates: ty::GenericPredicates<'tcx>) -> bool {
67 self.skeleton().visit_predicates(predicates)
71 struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> {
72 def_id_visitor: &'v mut V,
73 visited_opaque_tys: FxHashSet<DefId>,
74 dummy: PhantomData<TyCtxt<'tcx>>,
77 impl<'tcx, V> DefIdVisitorSkeleton<'_, 'tcx, V>
79 V: DefIdVisitor<'tcx> + ?Sized,
81 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> bool {
82 let TraitRef { def_id, substs } = trait_ref;
83 self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref.print_only_trait_path())
84 || (!self.def_id_visitor.shallow() && substs.visit_with(self))
87 fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> bool {
88 match predicate.skip_binders() {
89 ty::PredicateAtom::Trait(ty::TraitPredicate { trait_ref }, _) => {
90 self.visit_trait(trait_ref)
92 ty::PredicateAtom::Projection(ty::ProjectionPredicate { projection_ty, ty }) => {
94 || self.visit_trait(projection_ty.trait_ref(self.def_id_visitor.tcx()))
96 ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(ty, _region)) => {
99 ty::PredicateAtom::RegionOutlives(..) => false,
100 _ => bug!("unexpected predicate: {:?}", predicate),
104 fn visit_predicates(&mut self, predicates: ty::GenericPredicates<'tcx>) -> bool {
105 let ty::GenericPredicates { parent: _, predicates } = predicates;
106 for &(predicate, _span) in predicates {
107 if self.visit_predicate(predicate) {
115 impl<'tcx, V> TypeVisitor<'tcx> for DefIdVisitorSkeleton<'_, 'tcx, V>
117 V: DefIdVisitor<'tcx> + ?Sized,
119 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
120 let tcx = self.def_id_visitor.tcx();
121 // InternalSubsts are not visited here because they are visited below in `super_visit_with`.
123 ty::Adt(&ty::AdtDef { did: def_id, .. }, ..)
124 | ty::Foreign(def_id)
125 | ty::FnDef(def_id, ..)
126 | ty::Closure(def_id, ..)
127 | ty::Generator(def_id, ..) => {
128 if self.def_id_visitor.visit_def_id(def_id, "type", &ty) {
131 if self.def_id_visitor.shallow() {
134 // Default type visitor doesn't visit signatures of fn types.
135 // Something like `fn() -> Priv {my_func}` is considered a private type even if
136 // `my_func` is public, so we need to visit signatures.
137 if let ty::FnDef(..) = ty.kind {
138 if tcx.fn_sig(def_id).visit_with(self) {
142 // Inherent static methods don't have self type in substs.
143 // Something like `fn() {my_method}` type of the method
144 // `impl Pub<Priv> { pub fn my_method() {} }` is considered a private type,
145 // so we need to visit the self type additionally.
146 if let Some(assoc_item) = tcx.opt_associated_item(def_id) {
147 if let ty::ImplContainer(impl_def_id) = assoc_item.container {
148 if tcx.type_of(impl_def_id).visit_with(self) {
154 ty::Projection(proj) => {
155 if self.def_id_visitor.skip_assoc_tys() {
156 // Visitors searching for minimal visibility/reachability want to
157 // conservatively approximate associated types like `<Type as Trait>::Alias`
158 // as visible/reachable even if both `Type` and `Trait` are private.
159 // Ideally, associated types should be substituted in the same way as
160 // free type aliases, but this isn't done yet.
163 // This will also visit substs if necessary, so we don't need to recurse.
164 return self.visit_trait(proj.trait_ref(tcx));
166 ty::Dynamic(predicates, ..) => {
167 // All traits in the list are considered the "primary" part of the type
168 // and are visited by shallow visitors.
169 for predicate in predicates.skip_binder() {
170 let trait_ref = match predicate {
171 ty::ExistentialPredicate::Trait(trait_ref) => trait_ref,
172 ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx),
173 ty::ExistentialPredicate::AutoTrait(def_id) => {
174 ty::ExistentialTraitRef { def_id, substs: InternalSubsts::empty() }
177 let ty::ExistentialTraitRef { def_id, substs: _ } = trait_ref;
178 if self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref) {
183 ty::Opaque(def_id, ..) => {
184 // Skip repeated `Opaque`s to avoid infinite recursion.
185 if self.visited_opaque_tys.insert(def_id) {
186 // The intent is to treat `impl Trait1 + Trait2` identically to
187 // `dyn Trait1 + Trait2`. Therefore we ignore def-id of the opaque type itself
188 // (it either has no visibility, or its visibility is insignificant, like
189 // visibilities of type aliases) and recurse into predicates instead to go
190 // through the trait list (default type visitor doesn't visit those traits).
191 // All traits in the list are considered the "primary" part of the type
192 // and are visited by shallow visitors.
193 if self.visit_predicates(tcx.predicates_of(def_id)) {
198 // These types don't have their own def-ids (but may have subcomponents
199 // with def-ids that should be visited recursively).
215 | ty::GeneratorWitness(..) => {}
216 ty::Bound(..) | ty::Placeholder(..) | ty::Infer(..) => {
217 bug!("unexpected type: {:?}", ty)
221 !self.def_id_visitor.shallow() && ty.super_visit_with(self)
225 fn def_id_visibility<'tcx>(
228 ) -> (ty::Visibility, Span, &'static str) {
229 match def_id.as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id)) {
231 let vis = match tcx.hir().get(hir_id) {
232 Node::Item(item) => &item.vis,
233 Node::ForeignItem(foreign_item) => &foreign_item.vis,
234 Node::MacroDef(macro_def) => {
235 if attr::contains_name(¯o_def.attrs, sym::macro_export) {
236 return (ty::Visibility::Public, macro_def.span, "public");
241 Node::TraitItem(..) | Node::Variant(..) => {
242 return def_id_visibility(tcx, tcx.hir().get_parent_did(hir_id).to_def_id());
244 Node::ImplItem(impl_item) => {
245 match tcx.hir().get(tcx.hir().get_parent_item(hir_id)) {
246 Node::Item(item) => match &item.kind {
247 hir::ItemKind::Impl { of_trait: None, .. } => &impl_item.vis,
248 hir::ItemKind::Impl { of_trait: Some(trait_ref), .. } => {
249 return def_id_visibility(tcx, trait_ref.path.res.def_id());
251 kind => bug!("unexpected item kind: {:?}", kind),
253 node => bug!("unexpected node kind: {:?}", node),
256 Node::Ctor(vdata) => {
257 let parent_hir_id = tcx.hir().get_parent_node(hir_id);
258 match tcx.hir().get(parent_hir_id) {
259 Node::Variant(..) => {
260 let parent_did = tcx.hir().local_def_id(parent_hir_id);
261 let (mut ctor_vis, mut span, mut descr) =
262 def_id_visibility(tcx, parent_did.to_def_id());
264 let adt_def = tcx.adt_def(tcx.hir().get_parent_did(hir_id).to_def_id());
265 let ctor_did = tcx.hir().local_def_id(vdata.ctor_hir_id().unwrap());
266 let variant = adt_def.variant_with_ctor_id(ctor_did.to_def_id());
268 if variant.is_field_list_non_exhaustive()
269 && ctor_vis == ty::Visibility::Public
272 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
273 let attrs = tcx.get_attrs(variant.def_id);
275 attr::find_by_name(&attrs, sym::non_exhaustive).unwrap().span;
276 descr = "crate-visible";
279 return (ctor_vis, span, descr);
282 let item = match tcx.hir().get(parent_hir_id) {
283 Node::Item(item) => item,
284 node => bug!("unexpected node kind: {:?}", node),
286 let (mut ctor_vis, mut span, mut descr) = (
287 ty::Visibility::from_hir(&item.vis, parent_hir_id, tcx),
289 item.vis.node.descr(),
291 for field in vdata.fields() {
292 let field_vis = ty::Visibility::from_hir(&field.vis, hir_id, tcx);
293 if ctor_vis.is_at_least(field_vis, tcx) {
294 ctor_vis = field_vis;
295 span = field.vis.span;
296 descr = field.vis.node.descr();
300 // If the structure is marked as non_exhaustive then lower the
301 // visibility to within the crate.
302 if ctor_vis == ty::Visibility::Public {
304 tcx.adt_def(tcx.hir().get_parent_did(hir_id).to_def_id());
305 if adt_def.non_enum_variant().is_field_list_non_exhaustive() {
307 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
308 span = attr::find_by_name(&item.attrs, sym::non_exhaustive)
311 descr = "crate-visible";
315 return (ctor_vis, span, descr);
317 node => bug!("unexpected node kind: {:?}", node),
320 Node::Expr(expr) => {
322 ty::Visibility::Restricted(tcx.parent_module(expr.hir_id).to_def_id()),
327 node => bug!("unexpected node kind: {:?}", node),
329 (ty::Visibility::from_hir(vis, hir_id, tcx), vis.span, vis.node.descr())
332 let vis = tcx.visibility(def_id);
333 let descr = if vis == ty::Visibility::Public { "public" } else { "private" };
334 (vis, tcx.def_span(def_id), descr)
339 fn min(vis1: ty::Visibility, vis2: ty::Visibility, tcx: TyCtxt<'_>) -> ty::Visibility {
340 if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
343 ////////////////////////////////////////////////////////////////////////////////
344 /// Visitor used to determine if pub(restricted) is used anywhere in the crate.
346 /// This is done so that `private_in_public` warnings can be turned into hard errors
347 /// in crates that have been updated to use pub(restricted).
348 ////////////////////////////////////////////////////////////////////////////////
349 struct PubRestrictedVisitor<'tcx> {
351 has_pub_restricted: bool,
354 impl Visitor<'tcx> for PubRestrictedVisitor<'tcx> {
355 type Map = Map<'tcx>;
357 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
358 NestedVisitorMap::All(self.tcx.hir())
360 fn visit_vis(&mut self, vis: &'tcx hir::Visibility<'tcx>) {
361 self.has_pub_restricted = self.has_pub_restricted || vis.node.is_pub_restricted();
365 ////////////////////////////////////////////////////////////////////////////////
366 /// Visitor used to determine impl visibility and reachability.
367 ////////////////////////////////////////////////////////////////////////////////
369 struct FindMin<'a, 'tcx, VL: VisibilityLike> {
371 access_levels: &'a AccessLevels,
375 impl<'a, 'tcx, VL: VisibilityLike> DefIdVisitor<'tcx> for FindMin<'a, 'tcx, VL> {
376 fn tcx(&self) -> TyCtxt<'tcx> {
379 fn shallow(&self) -> bool {
382 fn skip_assoc_tys(&self) -> bool {
385 fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) -> bool {
386 self.min = VL::new_min(self, def_id);
391 trait VisibilityLike: Sized {
393 const SHALLOW: bool = false;
394 fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self;
396 // Returns an over-approximation (`skip_assoc_tys` = true) of visibility due to
397 // associated types for which we can't determine visibility precisely.
398 fn of_impl(hir_id: hir::HirId, tcx: TyCtxt<'_>, access_levels: &AccessLevels) -> Self {
399 let mut find = FindMin { tcx, access_levels, min: Self::MAX };
400 let def_id = tcx.hir().local_def_id(hir_id);
401 find.visit(tcx.type_of(def_id));
402 if let Some(trait_ref) = tcx.impl_trait_ref(def_id) {
403 find.visit_trait(trait_ref);
408 impl VisibilityLike for ty::Visibility {
409 const MAX: Self = ty::Visibility::Public;
410 fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self {
411 min(def_id_visibility(find.tcx, def_id).0, find.min, find.tcx)
414 impl VisibilityLike for Option<AccessLevel> {
415 const MAX: Self = Some(AccessLevel::Public);
416 // Type inference is very smart sometimes.
417 // It can make an impl reachable even some components of its type or trait are unreachable.
418 // E.g. methods of `impl ReachableTrait<UnreachableTy> for ReachableTy<UnreachableTy> { ... }`
419 // can be usable from other crates (#57264). So we skip substs when calculating reachability
420 // and consider an impl reachable if its "shallow" type and trait are reachable.
422 // The assumption we make here is that type-inference won't let you use an impl without knowing
423 // both "shallow" version of its self type and "shallow" version of its trait if it exists
424 // (which require reaching the `DefId`s in them).
425 const SHALLOW: bool = true;
426 fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self {
428 if let Some(def_id) = def_id.as_local() {
429 let hir_id = find.tcx.hir().as_local_hir_id(def_id);
430 find.access_levels.map.get(&hir_id).cloned()
439 ////////////////////////////////////////////////////////////////////////////////
440 /// The embargo visitor, used to determine the exports of the AST.
441 ////////////////////////////////////////////////////////////////////////////////
443 struct EmbargoVisitor<'tcx> {
446 /// Accessibility levels for reachable nodes.
447 access_levels: AccessLevels,
448 /// A set of pairs corresponding to modules, where the first module is
449 /// reachable via a macro that's defined in the second module. This cannot
450 /// be represented as reachable because it can't handle the following case:
452 /// pub mod n { // Should be `Public`
453 /// pub(crate) mod p { // Should *not* be accessible
454 /// pub fn f() -> i32 { 12 } // Must be `Reachable`
460 macro_reachable: FxHashSet<(hir::HirId, DefId)>,
461 /// Previous accessibility level; `None` means unreachable.
462 prev_level: Option<AccessLevel>,
463 /// Has something changed in the level map?
467 struct ReachEverythingInTheInterfaceVisitor<'a, 'tcx> {
468 access_level: Option<AccessLevel>,
470 ev: &'a mut EmbargoVisitor<'tcx>,
473 impl EmbargoVisitor<'tcx> {
474 fn get(&self, id: hir::HirId) -> Option<AccessLevel> {
475 self.access_levels.map.get(&id).cloned()
478 /// Updates node level and returns the updated level.
479 fn update(&mut self, id: hir::HirId, level: Option<AccessLevel>) -> Option<AccessLevel> {
480 let old_level = self.get(id);
481 // Accessibility levels can only grow.
482 if level > old_level {
483 self.access_levels.map.insert(id, level.unwrap());
494 access_level: Option<AccessLevel>,
495 ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
496 ReachEverythingInTheInterfaceVisitor {
497 access_level: cmp::min(access_level, Some(AccessLevel::Reachable)),
498 item_def_id: self.tcx.hir().local_def_id(item_id).to_def_id(),
503 /// Updates the item as being reachable through a macro defined in the given
504 /// module. Returns `true` if the level has changed.
505 fn update_macro_reachable(&mut self, reachable_mod: hir::HirId, defining_mod: DefId) -> bool {
506 if self.macro_reachable.insert((reachable_mod, defining_mod)) {
507 self.update_macro_reachable_mod(reachable_mod, defining_mod);
514 fn update_macro_reachable_mod(&mut self, reachable_mod: hir::HirId, defining_mod: DefId) {
515 let module_def_id = self.tcx.hir().local_def_id(reachable_mod);
516 let module = self.tcx.hir().get_module(module_def_id).0;
517 for item_id in module.item_ids {
518 let hir_id = item_id.id;
519 let item_def_id = self.tcx.hir().local_def_id(hir_id);
520 let def_kind = self.tcx.def_kind(item_def_id);
521 let item = self.tcx.hir().expect_item(hir_id);
522 let vis = ty::Visibility::from_hir(&item.vis, hir_id, self.tcx);
523 self.update_macro_reachable_def(hir_id, def_kind, vis, defining_mod);
525 if let Some(exports) = self.tcx.module_exports(module_def_id) {
526 for export in exports {
527 if export.vis.is_accessible_from(defining_mod, self.tcx) {
528 if let Res::Def(def_kind, def_id) = export.res {
529 let vis = def_id_visibility(self.tcx, def_id).0;
530 if let Some(def_id) = def_id.as_local() {
531 let hir_id = self.tcx.hir().as_local_hir_id(def_id);
532 self.update_macro_reachable_def(hir_id, def_kind, vis, defining_mod);
540 fn update_macro_reachable_def(
547 let level = Some(AccessLevel::Reachable);
548 if let ty::Visibility::Public = vis {
549 self.update(hir_id, level);
552 // No type privacy, so can be directly marked as reachable.
556 | DefKind::TraitAlias
557 | DefKind::TyAlias => {
558 if vis.is_accessible_from(module, self.tcx) {
559 self.update(hir_id, level);
563 // We can't use a module name as the final segment of a path, except
564 // in use statements. Since re-export checking doesn't consider
565 // hygiene these don't need to be marked reachable. The contents of
566 // the module, however may be reachable.
568 if vis.is_accessible_from(module, self.tcx) {
569 self.update_macro_reachable(hir_id, module);
573 DefKind::Struct | DefKind::Union => {
574 // While structs and unions have type privacy, their fields do
576 if let ty::Visibility::Public = vis {
577 let item = self.tcx.hir().expect_item(hir_id);
578 if let hir::ItemKind::Struct(ref struct_def, _)
579 | hir::ItemKind::Union(ref struct_def, _) = item.kind
581 for field in struct_def.fields() {
583 ty::Visibility::from_hir(&field.vis, field.hir_id, self.tcx);
584 if field_vis.is_accessible_from(module, self.tcx) {
585 self.reach(field.hir_id, level).ty();
589 bug!("item {:?} with DefKind {:?}", item, def_kind);
594 // These have type privacy, so are not reachable unless they're
595 // public, or are not namespaced at all.
598 | DefKind::ConstParam
599 | DefKind::Ctor(_, _)
608 | DefKind::LifetimeParam
609 | DefKind::ExternCrate
611 | DefKind::ForeignMod
617 | DefKind::Generator => (),
621 /// Given the path segments of a `ItemKind::Use`, then we need
622 /// to update the visibility of the intermediate use so that it isn't linted
623 /// by `unreachable_pub`.
625 /// This isn't trivial as `path.res` has the `DefId` of the eventual target
626 /// of the use statement not of the next intermediate use statement.
628 /// To do this, consider the last two segments of the path to our intermediate
629 /// use statement. We expect the penultimate segment to be a module and the
630 /// last segment to be the name of the item we are exporting. We can then
631 /// look at the items contained in the module for the use statement with that
632 /// name and update that item's visibility.
634 /// FIXME: This solution won't work with glob imports and doesn't respect
635 /// namespaces. See <https://github.com/rust-lang/rust/pull/57922#discussion_r251234202>.
636 fn update_visibility_of_intermediate_use_statements(
638 segments: &[hir::PathSegment<'_>],
640 if let Some([module, segment]) = segments.rchunks_exact(2).next() {
641 if let Some(item) = module
643 .and_then(|res| res.mod_def_id())
644 // If the module is `self`, i.e. the current crate,
645 // there will be no corresponding item.
646 .filter(|def_id| def_id.index != CRATE_DEF_INDEX || def_id.krate != LOCAL_CRATE)
648 def_id.as_local().map(|def_id| self.tcx.hir().as_local_hir_id(def_id))
650 .map(|module_hir_id| self.tcx.hir().expect_item(module_hir_id))
652 if let hir::ItemKind::Mod(m) = &item.kind {
653 for item_id in m.item_ids {
654 let item = self.tcx.hir().expect_item(item_id.id);
655 let def_id = self.tcx.hir().local_def_id(item_id.id);
656 if !self.tcx.hygienic_eq(segment.ident, item.ident, def_id.to_def_id()) {
659 if let hir::ItemKind::Use(..) = item.kind {
660 self.update(item.hir_id, Some(AccessLevel::Exported));
669 impl Visitor<'tcx> for EmbargoVisitor<'tcx> {
670 type Map = Map<'tcx>;
672 /// We want to visit items in the context of their containing
673 /// module and so forth, so supply a crate for doing a deep walk.
674 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
675 NestedVisitorMap::All(self.tcx.hir())
678 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
679 let inherited_item_level = match item.kind {
680 hir::ItemKind::Impl { .. } => {
681 Option::<AccessLevel>::of_impl(item.hir_id, self.tcx, &self.access_levels)
683 // Foreign modules inherit level from parents.
684 hir::ItemKind::ForeignMod(..) => self.prev_level,
685 // Other `pub` items inherit levels from parents.
686 hir::ItemKind::Const(..)
687 | hir::ItemKind::Enum(..)
688 | hir::ItemKind::ExternCrate(..)
689 | hir::ItemKind::GlobalAsm(..)
690 | hir::ItemKind::Fn(..)
691 | hir::ItemKind::Mod(..)
692 | hir::ItemKind::Static(..)
693 | hir::ItemKind::Struct(..)
694 | hir::ItemKind::Trait(..)
695 | hir::ItemKind::TraitAlias(..)
696 | hir::ItemKind::OpaqueTy(..)
697 | hir::ItemKind::TyAlias(..)
698 | hir::ItemKind::Union(..)
699 | hir::ItemKind::Use(..) => {
700 if item.vis.node.is_pub() {
708 // Update level of the item itself.
709 let item_level = self.update(item.hir_id, inherited_item_level);
711 // Update levels of nested things.
713 hir::ItemKind::Enum(ref def, _) => {
714 for variant in def.variants {
715 let variant_level = self.update(variant.id, item_level);
716 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
717 self.update(ctor_hir_id, item_level);
719 for field in variant.data.fields() {
720 self.update(field.hir_id, variant_level);
724 hir::ItemKind::Impl { ref of_trait, items, .. } => {
725 for impl_item_ref in items {
726 if of_trait.is_some() || impl_item_ref.vis.node.is_pub() {
727 self.update(impl_item_ref.id.hir_id, item_level);
731 hir::ItemKind::Trait(.., trait_item_refs) => {
732 for trait_item_ref in trait_item_refs {
733 self.update(trait_item_ref.id.hir_id, item_level);
736 hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => {
737 if let Some(ctor_hir_id) = def.ctor_hir_id() {
738 self.update(ctor_hir_id, item_level);
740 for field in def.fields() {
741 if field.vis.node.is_pub() {
742 self.update(field.hir_id, item_level);
746 hir::ItemKind::ForeignMod(ref foreign_mod) => {
747 for foreign_item in foreign_mod.items {
748 if foreign_item.vis.node.is_pub() {
749 self.update(foreign_item.hir_id, item_level);
753 hir::ItemKind::OpaqueTy(..)
754 | hir::ItemKind::Use(..)
755 | hir::ItemKind::Static(..)
756 | hir::ItemKind::Const(..)
757 | hir::ItemKind::GlobalAsm(..)
758 | hir::ItemKind::TyAlias(..)
759 | hir::ItemKind::Mod(..)
760 | hir::ItemKind::TraitAlias(..)
761 | hir::ItemKind::Fn(..)
762 | hir::ItemKind::ExternCrate(..) => {}
765 // Mark all items in interfaces of reachable items as reachable.
767 // The interface is empty.
768 hir::ItemKind::ExternCrate(..) => {}
769 // All nested items are checked by `visit_item`.
770 hir::ItemKind::Mod(..) => {}
771 // Re-exports are handled in `visit_mod`. However, in order to avoid looping over
772 // all of the items of a mod in `visit_mod` looking for use statements, we handle
773 // making sure that intermediate use statements have their visibilities updated here.
774 hir::ItemKind::Use(ref path, _) => {
775 if item_level.is_some() {
776 self.update_visibility_of_intermediate_use_statements(path.segments.as_ref());
779 // The interface is empty.
780 hir::ItemKind::GlobalAsm(..) => {}
781 hir::ItemKind::OpaqueTy(..) => {
782 // FIXME: This is some serious pessimization intended to workaround deficiencies
783 // in the reachability pass (`middle/reachable.rs`). Types are marked as link-time
784 // reachable if they are returned via `impl Trait`, even from private functions.
785 let exist_level = cmp::max(item_level, Some(AccessLevel::ReachableFromImplTrait));
786 self.reach(item.hir_id, exist_level).generics().predicates().ty();
789 hir::ItemKind::Const(..)
790 | hir::ItemKind::Static(..)
791 | hir::ItemKind::Fn(..)
792 | hir::ItemKind::TyAlias(..) => {
793 if item_level.is_some() {
794 self.reach(item.hir_id, item_level).generics().predicates().ty();
797 hir::ItemKind::Trait(.., trait_item_refs) => {
798 if item_level.is_some() {
799 self.reach(item.hir_id, item_level).generics().predicates();
801 for trait_item_ref in trait_item_refs {
802 let mut reach = self.reach(trait_item_ref.id.hir_id, item_level);
803 reach.generics().predicates();
805 if trait_item_ref.kind == AssocItemKind::Type
806 && !trait_item_ref.defaultness.has_value()
815 hir::ItemKind::TraitAlias(..) => {
816 if item_level.is_some() {
817 self.reach(item.hir_id, item_level).generics().predicates();
820 // Visit everything except for private impl items.
821 hir::ItemKind::Impl { items, .. } => {
822 if item_level.is_some() {
823 self.reach(item.hir_id, item_level).generics().predicates().ty().trait_ref();
825 for impl_item_ref in items {
826 let impl_item_level = self.get(impl_item_ref.id.hir_id);
827 if impl_item_level.is_some() {
828 self.reach(impl_item_ref.id.hir_id, impl_item_level)
837 // Visit everything, but enum variants have their own levels.
838 hir::ItemKind::Enum(ref def, _) => {
839 if item_level.is_some() {
840 self.reach(item.hir_id, item_level).generics().predicates();
842 for variant in def.variants {
843 let variant_level = self.get(variant.id);
844 if variant_level.is_some() {
845 for field in variant.data.fields() {
846 self.reach(field.hir_id, variant_level).ty();
848 // Corner case: if the variant is reachable, but its
849 // enum is not, make the enum reachable as well.
850 self.update(item.hir_id, variant_level);
854 // Visit everything, but foreign items have their own levels.
855 hir::ItemKind::ForeignMod(ref foreign_mod) => {
856 for foreign_item in foreign_mod.items {
857 let foreign_item_level = self.get(foreign_item.hir_id);
858 if foreign_item_level.is_some() {
859 self.reach(foreign_item.hir_id, foreign_item_level)
866 // Visit everything except for private fields.
867 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
868 if item_level.is_some() {
869 self.reach(item.hir_id, item_level).generics().predicates();
870 for field in struct_def.fields() {
871 let field_level = self.get(field.hir_id);
872 if field_level.is_some() {
873 self.reach(field.hir_id, field_level).ty();
880 let orig_level = mem::replace(&mut self.prev_level, item_level);
881 intravisit::walk_item(self, item);
882 self.prev_level = orig_level;
885 fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
886 // Blocks can have public items, for example impls, but they always
887 // start as completely private regardless of publicity of a function,
888 // constant, type, field, etc., in which this block resides.
889 let orig_level = mem::replace(&mut self.prev_level, None);
890 intravisit::walk_block(self, b);
891 self.prev_level = orig_level;
894 fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, _sp: Span, id: hir::HirId) {
895 // This code is here instead of in visit_item so that the
896 // crate module gets processed as well.
897 if self.prev_level.is_some() {
898 let def_id = self.tcx.hir().local_def_id(id);
899 if let Some(exports) = self.tcx.module_exports(def_id) {
900 for export in exports.iter() {
901 if export.vis == ty::Visibility::Public {
902 if let Some(def_id) = export.res.opt_def_id() {
903 if let Some(def_id) = def_id.as_local() {
904 let hir_id = self.tcx.hir().as_local_hir_id(def_id);
905 self.update(hir_id, Some(AccessLevel::Exported));
913 intravisit::walk_mod(self, m, id);
916 fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef<'tcx>) {
917 if attr::find_transparency(&md.attrs, md.ast.macro_rules).0 != Transparency::Opaque {
918 self.update(md.hir_id, Some(AccessLevel::Public));
922 let macro_module_def_id =
923 ty::DefIdTree::parent(self.tcx, self.tcx.hir().local_def_id(md.hir_id).to_def_id())
925 // FIXME(#71104) Should really be using just `as_local_hir_id` but
926 // some `DefId` do not seem to have a corresponding HirId.
927 let hir_id = macro_module_def_id
929 .and_then(|def_id| self.tcx.hir().opt_local_def_id_to_hir_id(def_id));
930 let mut module_id = match hir_id {
931 Some(module_id) if self.tcx.hir().is_hir_id_module(module_id) => module_id,
932 // `module_id` doesn't correspond to a `mod`, return early (#63164, #65252).
935 let level = if md.vis.node.is_pub() { self.get(module_id) } else { None };
936 let new_level = self.update(md.hir_id, level);
937 if new_level.is_none() {
942 let changed_reachability = self.update_macro_reachable(module_id, macro_module_def_id);
943 if changed_reachability || module_id == hir::CRATE_HIR_ID {
946 module_id = self.tcx.hir().get_parent_node(module_id);
951 impl ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
952 fn generics(&mut self) -> &mut Self {
953 for param in &self.ev.tcx.generics_of(self.item_def_id).params {
955 GenericParamDefKind::Lifetime => {}
956 GenericParamDefKind::Type { has_default, .. } => {
958 self.visit(self.ev.tcx.type_of(param.def_id));
961 GenericParamDefKind::Const => {
962 self.visit(self.ev.tcx.type_of(param.def_id));
969 fn predicates(&mut self) -> &mut Self {
970 self.visit_predicates(self.ev.tcx.predicates_of(self.item_def_id));
974 fn ty(&mut self) -> &mut Self {
975 self.visit(self.ev.tcx.type_of(self.item_def_id));
979 fn trait_ref(&mut self) -> &mut Self {
980 if let Some(trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) {
981 self.visit_trait(trait_ref);
987 impl DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
988 fn tcx(&self) -> TyCtxt<'tcx> {
991 fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) -> bool {
992 if let Some(def_id) = def_id.as_local() {
993 let hir_id = self.ev.tcx.hir().as_local_hir_id(def_id);
994 if let ((ty::Visibility::Public, ..), _)
995 | (_, Some(AccessLevel::ReachableFromImplTrait)) =
996 (def_id_visibility(self.tcx(), def_id.to_def_id()), self.access_level)
998 self.ev.update(hir_id, self.access_level);
1005 //////////////////////////////////////////////////////////////////////////////////////
1006 /// Name privacy visitor, checks privacy and reports violations.
1007 /// Most of name privacy checks are performed during the main resolution phase,
1008 /// or later in type checking when field accesses and associated items are resolved.
1009 /// This pass performs remaining checks for fields in struct expressions and patterns.
1010 //////////////////////////////////////////////////////////////////////////////////////
1012 struct NamePrivacyVisitor<'tcx> {
1014 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
1015 current_item: Option<hir::HirId>,
1018 impl<'tcx> NamePrivacyVisitor<'tcx> {
1019 /// Gets the type-checking results for the current body.
1020 /// As this will ICE if called outside bodies, only call when working with
1021 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
1023 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
1024 self.maybe_typeck_results
1025 .expect("`NamePrivacyVisitor::typeck_results` called outside of body")
1028 // Checks that a field in a struct constructor (expression or pattern) is accessible.
1031 use_ctxt: Span, // syntax context of the field name at the use site
1032 span: Span, // span of the field pattern, e.g., `x: 0`
1033 def: &'tcx ty::AdtDef, // definition of the struct or enum
1034 field: &'tcx ty::FieldDef,
1035 in_update_syntax: bool,
1037 // definition of the field
1038 let ident = Ident::new(kw::Invalid, use_ctxt);
1039 let current_hir = self.current_item.unwrap();
1040 let def_id = self.tcx.adjust_ident_and_get_scope(ident, def.did, current_hir).1;
1041 if !def.is_enum() && !field.vis.is_accessible_from(def_id, self.tcx) {
1042 let label = if in_update_syntax {
1043 format!("field `{}` is private", field.ident)
1045 "private field".to_string()
1052 "field `{}` of {} `{}` is private",
1054 def.variant_descr(),
1055 self.tcx.def_path_str(def.did)
1057 .span_label(span, label)
1063 impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> {
1064 type Map = Map<'tcx>;
1066 /// We want to visit items in the context of their containing
1067 /// module and so forth, so supply a crate for doing a deep walk.
1068 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1069 NestedVisitorMap::All(self.tcx.hir())
1072 fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) {
1073 // Don't visit nested modules, since we run a separate visitor walk
1074 // for each module in `privacy_access_levels`
1077 fn visit_nested_body(&mut self, body: hir::BodyId) {
1078 let old_maybe_typeck_results =
1079 self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
1080 let body = self.tcx.hir().body(body);
1081 self.visit_body(body);
1082 self.maybe_typeck_results = old_maybe_typeck_results;
1085 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1086 let orig_current_item = self.current_item.replace(item.hir_id);
1087 intravisit::walk_item(self, item);
1088 self.current_item = orig_current_item;
1091 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1092 if let hir::ExprKind::Struct(ref qpath, fields, ref base) = expr.kind {
1093 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
1094 let adt = self.typeck_results().expr_ty(expr).ty_adt_def().unwrap();
1095 let variant = adt.variant_of_res(res);
1096 if let Some(ref base) = *base {
1097 // If the expression uses FRU we need to make sure all the unmentioned fields
1098 // are checked for privacy (RFC 736). Rather than computing the set of
1099 // unmentioned fields, just check them all.
1100 for (vf_index, variant_field) in variant.fields.iter().enumerate() {
1101 let field = fields.iter().find(|f| {
1102 self.tcx.field_index(f.hir_id, self.typeck_results()) == vf_index
1104 let (use_ctxt, span) = match field {
1105 Some(field) => (field.ident.span, field.span),
1106 None => (base.span, base.span),
1108 self.check_field(use_ctxt, span, adt, variant_field, true);
1111 for field in fields {
1112 let use_ctxt = field.ident.span;
1113 let index = self.tcx.field_index(field.hir_id, self.typeck_results());
1114 self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false);
1119 intravisit::walk_expr(self, expr);
1122 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
1123 if let PatKind::Struct(ref qpath, fields, _) = pat.kind {
1124 let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
1125 let adt = self.typeck_results().pat_ty(pat).ty_adt_def().unwrap();
1126 let variant = adt.variant_of_res(res);
1127 for field in fields {
1128 let use_ctxt = field.ident.span;
1129 let index = self.tcx.field_index(field.hir_id, self.typeck_results());
1130 self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false);
1134 intravisit::walk_pat(self, pat);
1138 ////////////////////////////////////////////////////////////////////////////////////////////
1139 /// Type privacy visitor, checks types for privacy and reports violations.
1140 /// Both explicitly written types and inferred types of expressions and patters are checked.
1141 /// Checks are performed on "semantic" types regardless of names and their hygiene.
1142 ////////////////////////////////////////////////////////////////////////////////////////////
1144 struct TypePrivacyVisitor<'tcx> {
1146 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
1147 current_item: LocalDefId,
1151 impl<'tcx> TypePrivacyVisitor<'tcx> {
1152 /// Gets the type-checking results for the current body.
1153 /// As this will ICE if called outside bodies, only call when working with
1154 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
1156 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
1157 self.maybe_typeck_results
1158 .expect("`TypePrivacyVisitor::typeck_results` called outside of body")
1161 fn item_is_accessible(&self, did: DefId) -> bool {
1162 def_id_visibility(self.tcx, did)
1164 .is_accessible_from(self.current_item.to_def_id(), self.tcx)
1167 // Take node-id of an expression or pattern and check its type for privacy.
1168 fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
1170 let typeck_results = self.typeck_results();
1171 if self.visit(typeck_results.node_type(id)) || self.visit(typeck_results.node_substs(id)) {
1174 if let Some(adjustments) = typeck_results.adjustments().get(id) {
1175 for adjustment in adjustments {
1176 if self.visit(adjustment.target) {
1184 fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1185 let is_error = !self.item_is_accessible(def_id);
1189 .struct_span_err(self.span, &format!("{} `{}` is private", kind, descr))
1190 .span_label(self.span, &format!("private {}", kind))
1197 impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> {
1198 type Map = Map<'tcx>;
1200 /// We want to visit items in the context of their containing
1201 /// module and so forth, so supply a crate for doing a deep walk.
1202 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1203 NestedVisitorMap::All(self.tcx.hir())
1206 fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) {
1207 // Don't visit nested modules, since we run a separate visitor walk
1208 // for each module in `privacy_access_levels`
1211 fn visit_nested_body(&mut self, body: hir::BodyId) {
1212 let old_maybe_typeck_results =
1213 self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
1214 let body = self.tcx.hir().body(body);
1215 self.visit_body(body);
1216 self.maybe_typeck_results = old_maybe_typeck_results;
1219 fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) {
1220 self.span = hir_ty.span;
1221 if let Some(typeck_results) = self.maybe_typeck_results {
1223 if self.visit(typeck_results.node_type(hir_ty.hir_id)) {
1227 // Types in signatures.
1228 // FIXME: This is very ineffective. Ideally each HIR type should be converted
1229 // into a semantic type only once and the result should be cached somehow.
1230 if self.visit(rustc_typeck::hir_ty_to_ty(self.tcx, hir_ty)) {
1235 intravisit::walk_ty(self, hir_ty);
1238 fn visit_trait_ref(&mut self, trait_ref: &'tcx hir::TraitRef<'tcx>) {
1239 self.span = trait_ref.path.span;
1240 if self.maybe_typeck_results.is_none() {
1241 // Avoid calling `hir_trait_to_predicates` in bodies, it will ICE.
1242 // The traits' privacy in bodies is already checked as a part of trait object types.
1243 let bounds = rustc_typeck::hir_trait_to_predicates(
1246 // NOTE: This isn't really right, but the actual type doesn't matter here. It's
1247 // just required by `ty::TraitRef`.
1248 self.tcx.types.never,
1251 for (trait_predicate, _, _) in bounds.trait_bounds {
1252 if self.visit_trait(trait_predicate.skip_binder()) {
1257 for (poly_predicate, _) in bounds.projection_bounds {
1259 if self.visit(poly_predicate.skip_binder().ty)
1260 || self.visit_trait(poly_predicate.skip_binder().projection_ty.trait_ref(tcx))
1267 intravisit::walk_trait_ref(self, trait_ref);
1270 // Check types of expressions
1271 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1272 if self.check_expr_pat_type(expr.hir_id, expr.span) {
1273 // Do not check nested expressions if the error already happened.
1277 hir::ExprKind::Assign(_, ref rhs, _) | hir::ExprKind::Match(ref rhs, ..) => {
1278 // Do not report duplicate errors for `x = y` and `match x { ... }`.
1279 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
1283 hir::ExprKind::MethodCall(_, span, _, _) => {
1284 // Method calls have to be checked specially.
1286 if let Some(def_id) = self.typeck_results().type_dependent_def_id(expr.hir_id) {
1287 if self.visit(self.tcx.type_of(def_id)) {
1293 .delay_span_bug(expr.span, "no type-dependent def for method call");
1299 intravisit::walk_expr(self, expr);
1302 // Prohibit access to associated items with insufficient nominal visibility.
1304 // Additionally, until better reachability analysis for macros 2.0 is available,
1305 // we prohibit access to private statics from other crates, this allows to give
1306 // more code internal visibility at link time. (Access to private functions
1307 // is already prohibited by type privacy for function types.)
1308 fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) {
1309 let def = match qpath {
1310 hir::QPath::Resolved(_, path) => match path.res {
1311 Res::Def(kind, def_id) => Some((kind, def_id)),
1314 hir::QPath::TypeRelative(..) => self
1315 .maybe_typeck_results
1316 .and_then(|typeck_results| typeck_results.type_dependent_def(id)),
1318 let def = def.filter(|(kind, _)| match kind {
1319 DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static => true,
1322 if let Some((kind, def_id)) = def {
1323 let is_local_static =
1324 if let DefKind::Static = kind { def_id.is_local() } else { false };
1325 if !self.item_is_accessible(def_id) && !is_local_static {
1326 let sess = self.tcx.sess;
1327 let sm = sess.source_map();
1328 let name = match qpath {
1329 hir::QPath::Resolved(_, path) => sm.span_to_snippet(path.span).ok(),
1330 hir::QPath::TypeRelative(_, segment) => Some(segment.ident.to_string()),
1332 let kind = kind.descr(def_id);
1333 let msg = match name {
1334 Some(name) => format!("{} `{}` is private", kind, name),
1335 None => format!("{} is private", kind),
1337 sess.struct_span_err(span, &msg)
1338 .span_label(span, &format!("private {}", kind))
1344 intravisit::walk_qpath(self, qpath, id, span);
1347 // Check types of patterns.
1348 fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) {
1349 if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
1350 // Do not check nested patterns if the error already happened.
1354 intravisit::walk_pat(self, pattern);
1357 fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) {
1358 if let Some(ref init) = local.init {
1359 if self.check_expr_pat_type(init.hir_id, init.span) {
1360 // Do not report duplicate errors for `let x = y`.
1365 intravisit::walk_local(self, local);
1368 // Check types in item interfaces.
1369 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1370 let orig_current_item =
1371 mem::replace(&mut self.current_item, self.tcx.hir().local_def_id(item.hir_id));
1372 let old_maybe_typeck_results = self.maybe_typeck_results.take();
1373 intravisit::walk_item(self, item);
1374 self.maybe_typeck_results = old_maybe_typeck_results;
1375 self.current_item = orig_current_item;
1379 impl DefIdVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1380 fn tcx(&self) -> TyCtxt<'tcx> {
1383 fn visit_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1384 self.check_def_id(def_id, kind, descr)
1388 ///////////////////////////////////////////////////////////////////////////////
1389 /// Obsolete visitors for checking for private items in public interfaces.
1390 /// These visitors are supposed to be kept in frozen state and produce an
1391 /// "old error node set". For backward compatibility the new visitor reports
1392 /// warnings instead of hard errors when the erroneous node is not in this old set.
1393 ///////////////////////////////////////////////////////////////////////////////
1395 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1397 access_levels: &'a AccessLevels,
1399 // Set of errors produced by this obsolete visitor.
1400 old_error_set: HirIdSet,
1403 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1404 inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
1405 /// Whether the type refers to private types.
1406 contains_private: bool,
1407 /// Whether we've recurred at all (i.e., if we're pointing at the
1408 /// first type on which `visit_ty` was called).
1409 at_outer_type: bool,
1410 /// Whether that first type is a public path.
1411 outer_type_is_public_path: bool,
1414 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1415 fn path_is_private_type(&self, path: &hir::Path<'_>) -> bool {
1416 let did = match path.res {
1417 Res::PrimTy(..) | Res::SelfTy(..) | Res::Err => return false,
1418 res => res.def_id(),
1421 // A path can only be private if:
1422 // it's in this crate...
1423 if let Some(did) = did.as_local() {
1424 // .. and it corresponds to a private type in the AST (this returns
1425 // `None` for type parameters).
1426 match self.tcx.hir().find(self.tcx.hir().as_local_hir_id(did)) {
1427 Some(Node::Item(ref item)) => !item.vis.node.is_pub(),
1428 Some(_) | None => false,
1435 fn trait_is_public(&self, trait_id: hir::HirId) -> bool {
1436 // FIXME: this would preferably be using `exported_items`, but all
1437 // traits are exported currently (see `EmbargoVisitor.exported_trait`).
1438 self.access_levels.is_public(trait_id)
1441 fn check_generic_bound(&mut self, bound: &hir::GenericBound<'_>) {
1442 if let hir::GenericBound::Trait(ref trait_ref, _) = *bound {
1443 if self.path_is_private_type(&trait_ref.trait_ref.path) {
1444 self.old_error_set.insert(trait_ref.trait_ref.hir_ref_id);
1449 fn item_is_public(&self, id: &hir::HirId, vis: &hir::Visibility<'_>) -> bool {
1450 self.access_levels.is_reachable(*id) || vis.node.is_pub()
1454 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1455 type Map = intravisit::ErasedMap<'v>;
1457 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1458 NestedVisitorMap::None
1461 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
1462 if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = ty.kind {
1463 if self.inner.path_is_private_type(path) {
1464 self.contains_private = true;
1465 // Found what we're looking for, so let's stop working.
1469 if let hir::TyKind::Path(_) = ty.kind {
1470 if self.at_outer_type {
1471 self.outer_type_is_public_path = true;
1474 self.at_outer_type = false;
1475 intravisit::walk_ty(self, ty)
1478 // Don't want to recurse into `[, .. expr]`.
1479 fn visit_expr(&mut self, _: &hir::Expr<'_>) {}
1482 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1483 type Map = Map<'tcx>;
1485 /// We want to visit items in the context of their containing
1486 /// module and so forth, so supply a crate for doing a deep walk.
1487 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1488 NestedVisitorMap::All(self.tcx.hir())
1491 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1493 // Contents of a private mod can be re-exported, so we need
1494 // to check internals.
1495 hir::ItemKind::Mod(_) => {}
1497 // An `extern {}` doesn't introduce a new privacy
1498 // namespace (the contents have their own privacies).
1499 hir::ItemKind::ForeignMod(_) => {}
1501 hir::ItemKind::Trait(.., ref bounds, _) => {
1502 if !self.trait_is_public(item.hir_id) {
1506 for bound in bounds.iter() {
1507 self.check_generic_bound(bound)
1511 // Impls need some special handling to try to offer useful
1512 // error messages without (too many) false positives
1513 // (i.e., we could just return here to not check them at
1514 // all, or some worse estimation of whether an impl is
1515 // publicly visible).
1516 hir::ItemKind::Impl { generics: ref g, ref of_trait, ref self_ty, items, .. } => {
1517 // `impl [... for] Private` is never visible.
1518 let self_contains_private;
1519 // `impl [... for] Public<...>`, but not `impl [... for]
1520 // Vec<Public>` or `(Public,)`, etc.
1521 let self_is_public_path;
1523 // Check the properties of the `Self` type:
1525 let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
1527 contains_private: false,
1528 at_outer_type: true,
1529 outer_type_is_public_path: false,
1531 visitor.visit_ty(&self_ty);
1532 self_contains_private = visitor.contains_private;
1533 self_is_public_path = visitor.outer_type_is_public_path;
1536 // Miscellaneous info about the impl:
1538 // `true` iff this is `impl Private for ...`.
1539 let not_private_trait = of_trait.as_ref().map_or(
1540 true, // no trait counts as public trait
1542 let did = tr.path.res.def_id();
1544 if let Some(did) = did.as_local() {
1545 self.trait_is_public(self.tcx.hir().as_local_hir_id(did))
1547 true // external traits must be public
1552 // `true` iff this is a trait impl or at least one method is public.
1554 // `impl Public { $( fn ...() {} )* }` is not visible.
1556 // This is required over just using the methods' privacy
1557 // directly because we might have `impl<T: Foo<Private>> ...`,
1558 // and we shouldn't warn about the generics if all the methods
1559 // are private (because `T` won't be visible externally).
1560 let trait_or_some_public_method = of_trait.is_some()
1561 || items.iter().any(|impl_item_ref| {
1562 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1563 match impl_item.kind {
1564 hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) => {
1565 self.access_levels.is_reachable(impl_item_ref.id.hir_id)
1567 hir::ImplItemKind::TyAlias(_) => false,
1571 if !self_contains_private && not_private_trait && trait_or_some_public_method {
1572 intravisit::walk_generics(self, g);
1576 for impl_item_ref in items {
1577 // This is where we choose whether to walk down
1578 // further into the impl to check its items. We
1579 // should only walk into public items so that we
1580 // don't erroneously report errors for private
1581 // types in private items.
1582 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1583 match impl_item.kind {
1584 hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..)
1586 .item_is_public(&impl_item.hir_id, &impl_item.vis) =>
1588 intravisit::walk_impl_item(self, impl_item)
1590 hir::ImplItemKind::TyAlias(..) => {
1591 intravisit::walk_impl_item(self, impl_item)
1598 // Any private types in a trait impl fall into three
1600 // 1. mentioned in the trait definition
1601 // 2. mentioned in the type params/generics
1602 // 3. mentioned in the associated types of the impl
1604 // Those in 1. can only occur if the trait is in
1605 // this crate and will've been warned about on the
1606 // trait definition (there's no need to warn twice
1607 // so we don't check the methods).
1609 // Those in 2. are warned via walk_generics and this
1611 intravisit::walk_path(self, &tr.path);
1613 // Those in 3. are warned with this call.
1614 for impl_item_ref in items {
1615 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1616 if let hir::ImplItemKind::TyAlias(ref ty) = impl_item.kind {
1622 } else if of_trait.is_none() && self_is_public_path {
1623 // `impl Public<Private> { ... }`. Any public static
1624 // methods will be visible as `Public::foo`.
1625 let mut found_pub_static = false;
1626 for impl_item_ref in items {
1627 if self.item_is_public(&impl_item_ref.id.hir_id, &impl_item_ref.vis) {
1628 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1629 match impl_item_ref.kind {
1630 AssocItemKind::Const => {
1631 found_pub_static = true;
1632 intravisit::walk_impl_item(self, impl_item);
1634 AssocItemKind::Fn { has_self: false } => {
1635 found_pub_static = true;
1636 intravisit::walk_impl_item(self, impl_item);
1642 if found_pub_static {
1643 intravisit::walk_generics(self, g)
1649 // `type ... = ...;` can contain private types, because
1650 // we're introducing a new name.
1651 hir::ItemKind::TyAlias(..) => return,
1653 // Not at all public, so we don't care.
1654 _ if !self.item_is_public(&item.hir_id, &item.vis) => {
1661 // We've carefully constructed it so that if we're here, then
1662 // any `visit_ty`'s will be called on things that are in
1663 // public signatures, i.e., things that we're interested in for
1665 intravisit::walk_item(self, item);
1668 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1669 for param in generics.params {
1670 for bound in param.bounds {
1671 self.check_generic_bound(bound);
1674 for predicate in generics.where_clause.predicates {
1676 hir::WherePredicate::BoundPredicate(bound_pred) => {
1677 for bound in bound_pred.bounds.iter() {
1678 self.check_generic_bound(bound)
1681 hir::WherePredicate::RegionPredicate(_) => {}
1682 hir::WherePredicate::EqPredicate(eq_pred) => {
1683 self.visit_ty(&eq_pred.rhs_ty);
1689 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
1690 if self.access_levels.is_reachable(item.hir_id) {
1691 intravisit::walk_foreign_item(self, item)
1695 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
1696 if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = t.kind {
1697 if self.path_is_private_type(path) {
1698 self.old_error_set.insert(t.hir_id);
1701 intravisit::walk_ty(self, t)
1706 v: &'tcx hir::Variant<'tcx>,
1707 g: &'tcx hir::Generics<'tcx>,
1708 item_id: hir::HirId,
1710 if self.access_levels.is_reachable(v.id) {
1711 self.in_variant = true;
1712 intravisit::walk_variant(self, v, g, item_id);
1713 self.in_variant = false;
1717 fn visit_struct_field(&mut self, s: &'tcx hir::StructField<'tcx>) {
1718 if s.vis.node.is_pub() || self.in_variant {
1719 intravisit::walk_struct_field(self, s);
1723 // We don't need to introspect into these at all: an
1724 // expression/block context can't possibly contain exported things.
1725 // (Making them no-ops stops us from traversing the whole AST without
1726 // having to be super careful about our `walk_...` calls above.)
1727 fn visit_block(&mut self, _: &'tcx hir::Block<'tcx>) {}
1728 fn visit_expr(&mut self, _: &'tcx hir::Expr<'tcx>) {}
1731 ///////////////////////////////////////////////////////////////////////////////
1732 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1733 /// finds any private components in it.
1734 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1735 /// and traits in public interfaces.
1736 ///////////////////////////////////////////////////////////////////////////////
1738 struct SearchInterfaceForPrivateItemsVisitor<'tcx> {
1740 item_id: hir::HirId,
1743 /// The visitor checks that each component type is at least this visible.
1744 required_visibility: ty::Visibility,
1745 has_pub_restricted: bool,
1746 has_old_errors: bool,
1750 impl SearchInterfaceForPrivateItemsVisitor<'tcx> {
1751 fn generics(&mut self) -> &mut Self {
1752 for param in &self.tcx.generics_of(self.item_def_id).params {
1754 GenericParamDefKind::Lifetime => {}
1755 GenericParamDefKind::Type { has_default, .. } => {
1757 self.visit(self.tcx.type_of(param.def_id));
1760 GenericParamDefKind::Const => {
1761 self.visit(self.tcx.type_of(param.def_id));
1768 fn predicates(&mut self) -> &mut Self {
1769 // N.B., we use `explicit_predicates_of` and not `predicates_of`
1770 // because we don't want to report privacy errors due to where
1771 // clauses that the compiler inferred. We only want to
1772 // consider the ones that the user wrote. This is important
1773 // for the inferred outlives rules; see
1774 // `src/test/ui/rfc-2093-infer-outlives/privacy.rs`.
1775 self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id));
1779 fn ty(&mut self) -> &mut Self {
1780 self.visit(self.tcx.type_of(self.item_def_id));
1784 fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1785 if self.leaks_private_dep(def_id) {
1786 self.tcx.struct_span_lint_hir(
1787 lint::builtin::EXPORTED_PRIVATE_DEPENDENCIES,
1791 lint.build(&format!(
1792 "{} `{}` from private dependency '{}' in public \
1796 self.tcx.crate_name(def_id.krate)
1803 let hir_id = match def_id.as_local() {
1804 Some(def_id) => self.tcx.hir().as_local_hir_id(def_id),
1805 None => return false,
1808 let (vis, vis_span, vis_descr) = def_id_visibility(self.tcx, def_id);
1809 if !vis.is_at_least(self.required_visibility, self.tcx) {
1810 let make_msg = || format!("{} {} `{}` in public interface", vis_descr, kind, descr);
1811 if self.has_pub_restricted || self.has_old_errors || self.in_assoc_ty {
1812 let mut err = if kind == "trait" {
1813 struct_span_err!(self.tcx.sess, self.span, E0445, "{}", make_msg())
1815 struct_span_err!(self.tcx.sess, self.span, E0446, "{}", make_msg())
1817 err.span_label(self.span, format!("can't leak {} {}", vis_descr, kind));
1818 err.span_label(vis_span, format!("`{}` declared as {}", descr, vis_descr));
1821 let err_code = if kind == "trait" { "E0445" } else { "E0446" };
1822 self.tcx.struct_span_lint_hir(
1823 lint::builtin::PRIVATE_IN_PUBLIC,
1826 |lint| lint.build(&format!("{} (error {})", make_msg(), err_code)).emit(),
1834 /// An item is 'leaked' from a private dependency if all
1835 /// of the following are true:
1836 /// 1. It's contained within a public type
1837 /// 2. It comes from a private crate
1838 fn leaks_private_dep(&self, item_id: DefId) -> bool {
1839 let ret = self.required_visibility == ty::Visibility::Public
1840 && self.tcx.is_private_dep(item_id.krate);
1842 log::debug!("leaks_private_dep(item_id={:?})={}", item_id, ret);
1847 impl DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> {
1848 fn tcx(&self) -> TyCtxt<'tcx> {
1851 fn visit_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1852 self.check_def_id(def_id, kind, descr)
1856 struct PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1858 has_pub_restricted: bool,
1859 old_error_set: &'a HirIdSet,
1862 impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1865 item_id: hir::HirId,
1866 required_visibility: ty::Visibility,
1867 ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> {
1868 let mut has_old_errors = false;
1870 // Slow path taken only if there any errors in the crate.
1871 for &id in self.old_error_set {
1872 // Walk up the nodes until we find `item_id` (or we hit a root).
1876 has_old_errors = true;
1879 let parent = self.tcx.hir().get_parent_node(id);
1891 SearchInterfaceForPrivateItemsVisitor {
1894 item_def_id: self.tcx.hir().local_def_id(item_id).to_def_id(),
1895 span: self.tcx.hir().span(item_id),
1896 required_visibility,
1897 has_pub_restricted: self.has_pub_restricted,
1903 fn check_assoc_item(
1906 assoc_item_kind: AssocItemKind,
1907 defaultness: hir::Defaultness,
1908 vis: ty::Visibility,
1910 let mut check = self.check(hir_id, vis);
1912 let (check_ty, is_assoc_ty) = match assoc_item_kind {
1913 AssocItemKind::Const | AssocItemKind::Fn { .. } => (true, false),
1914 AssocItemKind::Type => (defaultness.has_value(), true),
1916 check.in_assoc_ty = is_assoc_ty;
1917 check.generics().predicates();
1924 impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1925 type Map = Map<'tcx>;
1927 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1928 NestedVisitorMap::OnlyBodies(self.tcx.hir())
1931 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1933 let item_visibility = ty::Visibility::from_hir(&item.vis, item.hir_id, tcx);
1936 // Crates are always public.
1937 hir::ItemKind::ExternCrate(..) => {}
1938 // All nested items are checked by `visit_item`.
1939 hir::ItemKind::Mod(..) => {}
1940 // Checked in resolve.
1941 hir::ItemKind::Use(..) => {}
1943 hir::ItemKind::GlobalAsm(..) => {}
1944 // Subitems of these items have inherited publicity.
1945 hir::ItemKind::Const(..)
1946 | hir::ItemKind::Static(..)
1947 | hir::ItemKind::Fn(..)
1948 | hir::ItemKind::TyAlias(..) => {
1949 self.check(item.hir_id, item_visibility).generics().predicates().ty();
1951 hir::ItemKind::OpaqueTy(..) => {
1952 // `ty()` for opaque types is the underlying type,
1953 // it's not a part of interface, so we skip it.
1954 self.check(item.hir_id, item_visibility).generics().predicates();
1956 hir::ItemKind::Trait(.., trait_item_refs) => {
1957 self.check(item.hir_id, item_visibility).generics().predicates();
1959 for trait_item_ref in trait_item_refs {
1960 self.check_assoc_item(
1961 trait_item_ref.id.hir_id,
1962 trait_item_ref.kind,
1963 trait_item_ref.defaultness,
1968 hir::ItemKind::TraitAlias(..) => {
1969 self.check(item.hir_id, item_visibility).generics().predicates();
1971 hir::ItemKind::Enum(ref def, _) => {
1972 self.check(item.hir_id, item_visibility).generics().predicates();
1974 for variant in def.variants {
1975 for field in variant.data.fields() {
1976 self.check(field.hir_id, item_visibility).ty();
1980 // Subitems of foreign modules have their own publicity.
1981 hir::ItemKind::ForeignMod(ref foreign_mod) => {
1982 for foreign_item in foreign_mod.items {
1983 let vis = ty::Visibility::from_hir(&foreign_item.vis, item.hir_id, tcx);
1984 self.check(foreign_item.hir_id, vis).generics().predicates().ty();
1987 // Subitems of structs and unions have their own publicity.
1988 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
1989 self.check(item.hir_id, item_visibility).generics().predicates();
1991 for field in struct_def.fields() {
1992 let field_visibility = ty::Visibility::from_hir(&field.vis, item.hir_id, tcx);
1993 self.check(field.hir_id, min(item_visibility, field_visibility, tcx)).ty();
1996 // An inherent impl is public when its type is public
1997 // Subitems of inherent impls have their own publicity.
1998 // A trait impl is public when both its type and its trait are public
1999 // Subitems of trait impls have inherited publicity.
2000 hir::ItemKind::Impl { ref of_trait, items, .. } => {
2001 let impl_vis = ty::Visibility::of_impl(item.hir_id, tcx, &Default::default());
2002 self.check(item.hir_id, impl_vis).generics().predicates();
2003 for impl_item_ref in items {
2004 let impl_item = tcx.hir().impl_item(impl_item_ref.id);
2005 let impl_item_vis = if of_trait.is_none() {
2007 ty::Visibility::from_hir(&impl_item.vis, item.hir_id, tcx),
2014 self.check_assoc_item(
2015 impl_item_ref.id.hir_id,
2017 impl_item_ref.defaultness,
2026 pub fn provide(providers: &mut Providers) {
2027 *providers = Providers {
2028 privacy_access_levels,
2029 check_private_in_public,
2035 fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
2036 // Check privacy of names not checked in previous compilation stages.
2037 let mut visitor = NamePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: None };
2038 let (module, span, hir_id) = tcx.hir().get_module(module_def_id);
2040 intravisit::walk_mod(&mut visitor, module, hir_id);
2042 // Check privacy of explicitly written types and traits as well as
2043 // inferred types of expressions and patterns.
2045 TypePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id, span };
2046 intravisit::walk_mod(&mut visitor, module, hir_id);
2049 fn privacy_access_levels(tcx: TyCtxt<'_>, krate: CrateNum) -> &AccessLevels {
2050 assert_eq!(krate, LOCAL_CRATE);
2052 // Build up a set of all exported items in the AST. This is a set of all
2053 // items which are reachable from external crates based on visibility.
2054 let mut visitor = EmbargoVisitor {
2056 access_levels: Default::default(),
2057 macro_reachable: Default::default(),
2058 prev_level: Some(AccessLevel::Public),
2062 intravisit::walk_crate(&mut visitor, tcx.hir().krate());
2063 if visitor.changed {
2064 visitor.changed = false;
2069 visitor.update(hir::CRATE_HIR_ID, Some(AccessLevel::Public));
2071 tcx.arena.alloc(visitor.access_levels)
2074 fn check_private_in_public(tcx: TyCtxt<'_>, krate: CrateNum) {
2075 assert_eq!(krate, LOCAL_CRATE);
2077 let access_levels = tcx.privacy_access_levels(LOCAL_CRATE);
2079 let krate = tcx.hir().krate();
2081 let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
2083 access_levels: &access_levels,
2085 old_error_set: Default::default(),
2087 intravisit::walk_crate(&mut visitor, krate);
2089 let has_pub_restricted = {
2090 let mut pub_restricted_visitor = PubRestrictedVisitor { tcx, has_pub_restricted: false };
2091 intravisit::walk_crate(&mut pub_restricted_visitor, krate);
2092 pub_restricted_visitor.has_pub_restricted
2095 // Check for private types and traits in public interfaces.
2096 let mut visitor = PrivateItemsInPublicInterfacesVisitor {
2099 old_error_set: &visitor.old_error_set,
2101 krate.visit_all_item_likes(&mut DeepVisitor::new(&mut visitor));