1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
2 #![feature(in_band_lifetimes)]
4 #![recursion_limit = "256"]
7 use rustc::hir::map::Map;
9 use rustc::middle::privacy::{AccessLevel, AccessLevels};
10 use rustc::ty::fold::TypeVisitor;
11 use rustc::ty::query::Providers;
12 use rustc::ty::subst::InternalSubsts;
13 use rustc::ty::{self, GenericParamDefKind, TraitRef, Ty, TyCtxt, TypeFoldable};
14 use rustc_data_structures::fx::FxHashSet;
15 use rustc_errors::struct_span_err;
17 use rustc_hir::def::{DefKind, Res};
18 use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
19 use rustc_hir::intravisit::{self, DeepVisitor, NestedVisitorMap, Visitor};
20 use rustc_hir::{AssocItemKind, HirIdSet, Node, PatKind};
21 use rustc_span::hygiene::Transparency;
22 use rustc_span::symbol::{kw, sym};
24 use syntax::ast::Ident;
27 use std::marker::PhantomData;
28 use std::{cmp, fmt, mem};
30 use rustc_error_codes::*;
32 ////////////////////////////////////////////////////////////////////////////////
33 /// Generic infrastructure used to implement specific visitors below.
34 ////////////////////////////////////////////////////////////////////////////////
36 /// Implemented to visit all `DefId`s in a type.
37 /// Visiting `DefId`s is useful because visibilities and reachabilities are attached to them.
38 /// The idea is to visit "all components of a type", as documented in
39 /// https://github.com/rust-lang/rfcs/blob/master/text/2145-type-privacy.md#how-to-determine-visibility-of-a-type.
40 /// The default type visitor (`TypeVisitor`) does most of the job, but it has some shortcomings.
41 /// First, it doesn't have overridable `fn visit_trait_ref`, so we have to catch trait `DefId`s
42 /// manually. Second, it doesn't visit some type components like signatures of fn types, or traits
43 /// in `impl Trait`, see individual comments in `DefIdVisitorSkeleton::visit_ty`.
44 trait DefIdVisitor<'tcx> {
45 fn tcx(&self) -> TyCtxt<'tcx>;
46 fn shallow(&self) -> bool {
49 fn skip_assoc_tys(&self) -> bool {
52 fn visit_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool;
54 /// Not overridden, but used to actually visit types and traits.
55 fn skeleton(&mut self) -> DefIdVisitorSkeleton<'_, 'tcx, Self> {
56 DefIdVisitorSkeleton {
58 visited_opaque_tys: Default::default(),
59 dummy: Default::default(),
62 fn visit(&mut self, ty_fragment: impl TypeFoldable<'tcx>) -> bool {
63 ty_fragment.visit_with(&mut self.skeleton())
65 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> bool {
66 self.skeleton().visit_trait(trait_ref)
68 fn visit_predicates(&mut self, predicates: ty::GenericPredicates<'tcx>) -> bool {
69 self.skeleton().visit_predicates(predicates)
73 struct DefIdVisitorSkeleton<'v, 'tcx, V>
75 V: DefIdVisitor<'tcx> + ?Sized,
77 def_id_visitor: &'v mut V,
78 visited_opaque_tys: FxHashSet<DefId>,
79 dummy: PhantomData<TyCtxt<'tcx>>,
82 impl<'tcx, V> DefIdVisitorSkeleton<'_, 'tcx, V>
84 V: DefIdVisitor<'tcx> + ?Sized,
86 fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> bool {
87 let TraitRef { def_id, substs } = trait_ref;
88 self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref.print_only_trait_path())
89 || (!self.def_id_visitor.shallow() && substs.visit_with(self))
92 fn visit_predicates(&mut self, predicates: ty::GenericPredicates<'tcx>) -> bool {
93 let ty::GenericPredicates { parent: _, predicates } = predicates;
94 for (predicate, _span) in predicates {
96 ty::Predicate::Trait(poly_predicate) => {
97 let ty::TraitPredicate { trait_ref } = *poly_predicate.skip_binder();
98 if self.visit_trait(trait_ref) {
102 ty::Predicate::Projection(poly_predicate) => {
103 let ty::ProjectionPredicate { projection_ty, ty } =
104 *poly_predicate.skip_binder();
105 if ty.visit_with(self) {
108 if self.visit_trait(projection_ty.trait_ref(self.def_id_visitor.tcx())) {
112 ty::Predicate::TypeOutlives(poly_predicate) => {
113 let ty::OutlivesPredicate(ty, _region) = *poly_predicate.skip_binder();
114 if ty.visit_with(self) {
118 ty::Predicate::RegionOutlives(..) => {}
119 _ => bug!("unexpected predicate: {:?}", predicate),
126 impl<'tcx, V> TypeVisitor<'tcx> for DefIdVisitorSkeleton<'_, 'tcx, V>
128 V: DefIdVisitor<'tcx> + ?Sized,
130 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
131 let tcx = self.def_id_visitor.tcx();
132 // InternalSubsts are not visited here because they are visited below in `super_visit_with`.
134 ty::Adt(&ty::AdtDef { did: def_id, .. }, ..)
135 | ty::Foreign(def_id)
136 | ty::FnDef(def_id, ..)
137 | ty::Closure(def_id, ..)
138 | ty::Generator(def_id, ..) => {
139 if self.def_id_visitor.visit_def_id(def_id, "type", &ty) {
142 if self.def_id_visitor.shallow() {
145 // Default type visitor doesn't visit signatures of fn types.
146 // Something like `fn() -> Priv {my_func}` is considered a private type even if
147 // `my_func` is public, so we need to visit signatures.
148 if let ty::FnDef(..) = ty.kind {
149 if tcx.fn_sig(def_id).visit_with(self) {
153 // Inherent static methods don't have self type in substs.
154 // Something like `fn() {my_method}` type of the method
155 // `impl Pub<Priv> { pub fn my_method() {} }` is considered a private type,
156 // so we need to visit the self type additionally.
157 if let Some(assoc_item) = tcx.opt_associated_item(def_id) {
158 if let ty::ImplContainer(impl_def_id) = assoc_item.container {
159 if tcx.type_of(impl_def_id).visit_with(self) {
165 ty::Projection(proj) | ty::UnnormalizedProjection(proj) => {
166 if self.def_id_visitor.skip_assoc_tys() {
167 // Visitors searching for minimal visibility/reachability want to
168 // conservatively approximate associated types like `<Type as Trait>::Alias`
169 // as visible/reachable even if both `Type` and `Trait` are private.
170 // Ideally, associated types should be substituted in the same way as
171 // free type aliases, but this isn't done yet.
174 // This will also visit substs if necessary, so we don't need to recurse.
175 return self.visit_trait(proj.trait_ref(tcx));
177 ty::Dynamic(predicates, ..) => {
178 // All traits in the list are considered the "primary" part of the type
179 // and are visited by shallow visitors.
180 for predicate in *predicates.skip_binder() {
181 let trait_ref = match *predicate {
182 ty::ExistentialPredicate::Trait(trait_ref) => trait_ref,
183 ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx),
184 ty::ExistentialPredicate::AutoTrait(def_id) => {
185 ty::ExistentialTraitRef { def_id, substs: InternalSubsts::empty() }
188 let ty::ExistentialTraitRef { def_id, substs: _ } = trait_ref;
189 if self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref) {
194 ty::Opaque(def_id, ..) => {
195 // Skip repeated `Opaque`s to avoid infinite recursion.
196 if self.visited_opaque_tys.insert(def_id) {
197 // The intent is to treat `impl Trait1 + Trait2` identically to
198 // `dyn Trait1 + Trait2`. Therefore we ignore def-id of the opaque type itself
199 // (it either has no visibility, or its visibility is insignificant, like
200 // visibilities of type aliases) and recurse into predicates instead to go
201 // through the trait list (default type visitor doesn't visit those traits).
202 // All traits in the list are considered the "primary" part of the type
203 // and are visited by shallow visitors.
204 if self.visit_predicates(tcx.predicates_of(def_id)) {
209 // These types don't have their own def-ids (but may have subcomponents
210 // with def-ids that should be visited recursively).
226 | ty::GeneratorWitness(..) => {}
227 ty::Bound(..) | ty::Placeholder(..) | ty::Infer(..) => {
228 bug!("unexpected type: {:?}", ty)
232 !self.def_id_visitor.shallow() && ty.super_visit_with(self)
236 fn def_id_visibility<'tcx>(
239 ) -> (ty::Visibility, Span, &'static str) {
240 match tcx.hir().as_local_hir_id(def_id) {
242 let vis = match tcx.hir().get(hir_id) {
243 Node::Item(item) => &item.vis,
244 Node::ForeignItem(foreign_item) => &foreign_item.vis,
245 Node::MacroDef(macro_def) => {
246 if attr::contains_name(¯o_def.attrs, sym::macro_export) {
247 return (ty::Visibility::Public, macro_def.span, "public");
252 Node::TraitItem(..) | Node::Variant(..) => {
253 return def_id_visibility(tcx, tcx.hir().get_parent_did(hir_id));
255 Node::ImplItem(impl_item) => {
256 match tcx.hir().get(tcx.hir().get_parent_item(hir_id)) {
257 Node::Item(item) => match &item.kind {
258 hir::ItemKind::Impl(.., None, _, _) => &impl_item.vis,
259 hir::ItemKind::Impl(.., Some(trait_ref), _, _) => {
260 return def_id_visibility(tcx, trait_ref.path.res.def_id());
262 kind => bug!("unexpected item kind: {:?}", kind),
264 node => bug!("unexpected node kind: {:?}", node),
267 Node::Ctor(vdata) => {
268 let parent_hir_id = tcx.hir().get_parent_node(hir_id);
269 match tcx.hir().get(parent_hir_id) {
270 Node::Variant(..) => {
271 let parent_did = tcx.hir().local_def_id(parent_hir_id);
272 let (mut ctor_vis, mut span, mut descr) =
273 def_id_visibility(tcx, parent_did);
275 let adt_def = tcx.adt_def(tcx.hir().get_parent_did(hir_id));
276 let ctor_did = tcx.hir().local_def_id(vdata.ctor_hir_id().unwrap());
277 let variant = adt_def.variant_with_ctor_id(ctor_did);
279 if variant.is_field_list_non_exhaustive()
280 && ctor_vis == ty::Visibility::Public
283 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
284 let attrs = tcx.get_attrs(variant.def_id);
286 attr::find_by_name(&attrs, sym::non_exhaustive).unwrap().span;
287 descr = "crate-visible";
290 return (ctor_vis, span, descr);
293 let item = match tcx.hir().get(parent_hir_id) {
294 Node::Item(item) => item,
295 node => bug!("unexpected node kind: {:?}", node),
297 let (mut ctor_vis, mut span, mut descr) = (
298 ty::Visibility::from_hir(&item.vis, parent_hir_id, tcx),
300 item.vis.node.descr(),
302 for field in vdata.fields() {
303 let field_vis = ty::Visibility::from_hir(&field.vis, hir_id, tcx);
304 if ctor_vis.is_at_least(field_vis, tcx) {
305 ctor_vis = field_vis;
306 span = field.vis.span;
307 descr = field.vis.node.descr();
311 // If the structure is marked as non_exhaustive then lower the
312 // visibility to within the crate.
313 if ctor_vis == ty::Visibility::Public {
314 let adt_def = tcx.adt_def(tcx.hir().get_parent_did(hir_id));
315 if adt_def.non_enum_variant().is_field_list_non_exhaustive() {
317 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
318 span = attr::find_by_name(&item.attrs, sym::non_exhaustive)
321 descr = "crate-visible";
325 return (ctor_vis, span, descr);
327 node => bug!("unexpected node kind: {:?}", node),
330 Node::Expr(expr) => {
332 ty::Visibility::Restricted(tcx.hir().get_module_parent(expr.hir_id)),
337 node => bug!("unexpected node kind: {:?}", node),
339 (ty::Visibility::from_hir(vis, hir_id, tcx), vis.span, vis.node.descr())
342 let vis = tcx.visibility(def_id);
343 let descr = if vis == ty::Visibility::Public { "public" } else { "private" };
344 (vis, tcx.def_span(def_id), descr)
349 // Set the correct `TypeckTables` for the given `item_id` (or an empty table if
350 // there is no `TypeckTables` for the item).
351 fn item_tables<'a, 'tcx>(
354 empty_tables: &'a ty::TypeckTables<'tcx>,
355 ) -> &'a ty::TypeckTables<'tcx> {
356 let def_id = tcx.hir().local_def_id(hir_id);
357 if tcx.has_typeck_tables(def_id) { tcx.typeck_tables_of(def_id) } else { empty_tables }
360 fn min(vis1: ty::Visibility, vis2: ty::Visibility, tcx: TyCtxt<'_>) -> ty::Visibility {
361 if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
364 ////////////////////////////////////////////////////////////////////////////////
365 /// Visitor used to determine if pub(restricted) is used anywhere in the crate.
367 /// This is done so that `private_in_public` warnings can be turned into hard errors
368 /// in crates that have been updated to use pub(restricted).
369 ////////////////////////////////////////////////////////////////////////////////
370 struct PubRestrictedVisitor<'tcx> {
372 has_pub_restricted: bool,
375 impl Visitor<'tcx> for PubRestrictedVisitor<'tcx> {
376 type Map = Map<'tcx>;
378 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
379 NestedVisitorMap::All(&self.tcx.hir())
381 fn visit_vis(&mut self, vis: &'tcx hir::Visibility<'tcx>) {
382 self.has_pub_restricted = self.has_pub_restricted || vis.node.is_pub_restricted();
386 ////////////////////////////////////////////////////////////////////////////////
387 /// Visitor used to determine impl visibility and reachability.
388 ////////////////////////////////////////////////////////////////////////////////
390 struct FindMin<'a, 'tcx, VL: VisibilityLike> {
392 access_levels: &'a AccessLevels,
396 impl<'a, 'tcx, VL: VisibilityLike> DefIdVisitor<'tcx> for FindMin<'a, 'tcx, VL> {
397 fn tcx(&self) -> TyCtxt<'tcx> {
400 fn shallow(&self) -> bool {
403 fn skip_assoc_tys(&self) -> bool {
406 fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) -> bool {
407 self.min = VL::new_min(self, def_id);
412 trait VisibilityLike: Sized {
414 const SHALLOW: bool = false;
415 fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self;
417 // Returns an over-approximation (`skip_assoc_tys` = true) of visibility due to
418 // associated types for which we can't determine visibility precisely.
419 fn of_impl(hir_id: hir::HirId, tcx: TyCtxt<'_>, access_levels: &AccessLevels) -> Self {
420 let mut find = FindMin { tcx, access_levels, min: Self::MAX };
421 let def_id = tcx.hir().local_def_id(hir_id);
422 find.visit(tcx.type_of(def_id));
423 if let Some(trait_ref) = tcx.impl_trait_ref(def_id) {
424 find.visit_trait(trait_ref);
429 impl VisibilityLike for ty::Visibility {
430 const MAX: Self = ty::Visibility::Public;
431 fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self {
432 min(def_id_visibility(find.tcx, def_id).0, find.min, find.tcx)
435 impl VisibilityLike for Option<AccessLevel> {
436 const MAX: Self = Some(AccessLevel::Public);
437 // Type inference is very smart sometimes.
438 // It can make an impl reachable even some components of its type or trait are unreachable.
439 // E.g. methods of `impl ReachableTrait<UnreachableTy> for ReachableTy<UnreachableTy> { ... }`
440 // can be usable from other crates (#57264). So we skip substs when calculating reachability
441 // and consider an impl reachable if its "shallow" type and trait are reachable.
443 // The assumption we make here is that type-inference won't let you use an impl without knowing
444 // both "shallow" version of its self type and "shallow" version of its trait if it exists
445 // (which require reaching the `DefId`s in them).
446 const SHALLOW: bool = true;
447 fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self {
449 if let Some(hir_id) = find.tcx.hir().as_local_hir_id(def_id) {
450 find.access_levels.map.get(&hir_id).cloned()
459 ////////////////////////////////////////////////////////////////////////////////
460 /// The embargo visitor, used to determine the exports of the AST.
461 ////////////////////////////////////////////////////////////////////////////////
463 struct EmbargoVisitor<'tcx> {
466 /// Accessibility levels for reachable nodes.
467 access_levels: AccessLevels,
468 /// A set of pairs corresponding to modules, where the first module is
469 /// reachable via a macro that's defined in the second module. This cannot
470 /// be represented as reachable because it can't handle the following case:
472 /// pub mod n { // Should be `Public`
473 /// pub(crate) mod p { // Should *not* be accessible
474 /// pub fn f() -> i32 { 12 } // Must be `Reachable`
480 macro_reachable: FxHashSet<(hir::HirId, DefId)>,
481 /// Previous accessibility level; `None` means unreachable.
482 prev_level: Option<AccessLevel>,
483 /// Has something changed in the level map?
487 struct ReachEverythingInTheInterfaceVisitor<'a, 'tcx> {
488 access_level: Option<AccessLevel>,
490 ev: &'a mut EmbargoVisitor<'tcx>,
493 impl EmbargoVisitor<'tcx> {
494 fn get(&self, id: hir::HirId) -> Option<AccessLevel> {
495 self.access_levels.map.get(&id).cloned()
498 /// Updates node level and returns the updated level.
499 fn update(&mut self, id: hir::HirId, level: Option<AccessLevel>) -> Option<AccessLevel> {
500 let old_level = self.get(id);
501 // Accessibility levels can only grow.
502 if level > old_level {
503 self.access_levels.map.insert(id, level.unwrap());
514 access_level: Option<AccessLevel>,
515 ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
516 ReachEverythingInTheInterfaceVisitor {
517 access_level: cmp::min(access_level, Some(AccessLevel::Reachable)),
518 item_def_id: self.tcx.hir().local_def_id(item_id),
523 /// Updates the item as being reachable through a macro defined in the given
524 /// module. Returns `true` if the level has changed.
525 fn update_macro_reachable(&mut self, reachable_mod: hir::HirId, defining_mod: DefId) -> bool {
526 if self.macro_reachable.insert((reachable_mod, defining_mod)) {
527 self.update_macro_reachable_mod(reachable_mod, defining_mod);
534 fn update_macro_reachable_mod(&mut self, reachable_mod: hir::HirId, defining_mod: DefId) {
535 let module_def_id = self.tcx.hir().local_def_id(reachable_mod);
536 let module = self.tcx.hir().get_module(module_def_id).0;
537 for item_id in module.item_ids {
538 let hir_id = item_id.id;
539 let item_def_id = self.tcx.hir().local_def_id(hir_id);
540 if let Some(def_kind) = self.tcx.def_kind(item_def_id) {
541 let item = self.tcx.hir().expect_item(hir_id);
542 let vis = ty::Visibility::from_hir(&item.vis, hir_id, self.tcx);
543 self.update_macro_reachable_def(hir_id, def_kind, vis, defining_mod);
546 if let Some(exports) = self.tcx.module_exports(module_def_id) {
547 for export in exports {
548 if export.vis.is_accessible_from(defining_mod, self.tcx) {
549 if let Res::Def(def_kind, def_id) = export.res {
550 let vis = def_id_visibility(self.tcx, def_id).0;
551 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
552 self.update_macro_reachable_def(hir_id, def_kind, vis, defining_mod);
560 fn update_macro_reachable_def(
567 let level = Some(AccessLevel::Reachable);
568 if let ty::Visibility::Public = vis {
569 self.update(hir_id, level);
572 // No type privacy, so can be directly marked as reachable.
576 | DefKind::TraitAlias
577 | DefKind::TyAlias => {
578 if vis.is_accessible_from(module, self.tcx) {
579 self.update(hir_id, level);
583 // We can't use a module name as the final segment of a path, except
584 // in use statements. Since re-export checking doesn't consider
585 // hygiene these don't need to be marked reachable. The contents of
586 // the module, however may be reachable.
588 if vis.is_accessible_from(module, self.tcx) {
589 self.update_macro_reachable(hir_id, module);
593 DefKind::Struct | DefKind::Union => {
594 // While structs and unions have type privacy, their fields do
596 if let ty::Visibility::Public = vis {
597 let item = self.tcx.hir().expect_item(hir_id);
598 if let hir::ItemKind::Struct(ref struct_def, _)
599 | hir::ItemKind::Union(ref struct_def, _) = item.kind
601 for field in struct_def.fields() {
603 ty::Visibility::from_hir(&field.vis, field.hir_id, self.tcx);
604 if field_vis.is_accessible_from(module, self.tcx) {
605 self.reach(field.hir_id, level).ty();
609 bug!("item {:?} with DefKind {:?}", item, def_kind);
614 // These have type privacy, so are not reachable unless they're
618 | DefKind::AssocOpaqueTy
619 | DefKind::ConstParam
620 | DefKind::Ctor(_, _)
628 | DefKind::Variant => (),
632 /// Given the path segments of a `ItemKind::Use`, then we need
633 /// to update the visibility of the intermediate use so that it isn't linted
634 /// by `unreachable_pub`.
636 /// This isn't trivial as `path.res` has the `DefId` of the eventual target
637 /// of the use statement not of the next intermediate use statement.
639 /// To do this, consider the last two segments of the path to our intermediate
640 /// use statement. We expect the penultimate segment to be a module and the
641 /// last segment to be the name of the item we are exporting. We can then
642 /// look at the items contained in the module for the use statement with that
643 /// name and update that item's visibility.
645 /// FIXME: This solution won't work with glob imports and doesn't respect
646 /// namespaces. See <https://github.com/rust-lang/rust/pull/57922#discussion_r251234202>.
647 fn update_visibility_of_intermediate_use_statements(
649 segments: &[hir::PathSegment<'_>],
651 if let Some([module, segment]) = segments.rchunks_exact(2).next() {
652 if let Some(item) = module
654 .and_then(|res| res.mod_def_id())
655 .and_then(|def_id| self.tcx.hir().as_local_hir_id(def_id))
656 .map(|module_hir_id| self.tcx.hir().expect_item(module_hir_id))
658 if let hir::ItemKind::Mod(m) = &item.kind {
659 for item_id in m.item_ids.as_ref() {
660 let item = self.tcx.hir().expect_item(item_id.id);
661 let def_id = self.tcx.hir().local_def_id(item_id.id);
662 if !self.tcx.hygienic_eq(segment.ident, item.ident, def_id) {
665 if let hir::ItemKind::Use(..) = item.kind {
666 self.update(item.hir_id, Some(AccessLevel::Exported));
675 impl Visitor<'tcx> for EmbargoVisitor<'tcx> {
676 type Map = Map<'tcx>;
678 /// We want to visit items in the context of their containing
679 /// module and so forth, so supply a crate for doing a deep walk.
680 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
681 NestedVisitorMap::All(&self.tcx.hir())
684 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
685 let inherited_item_level = match item.kind {
686 hir::ItemKind::Impl(..) => {
687 Option::<AccessLevel>::of_impl(item.hir_id, self.tcx, &self.access_levels)
689 // Foreign modules inherit level from parents.
690 hir::ItemKind::ForeignMod(..) => self.prev_level,
691 // Other `pub` items inherit levels from parents.
692 hir::ItemKind::Const(..)
693 | hir::ItemKind::Enum(..)
694 | hir::ItemKind::ExternCrate(..)
695 | hir::ItemKind::GlobalAsm(..)
696 | hir::ItemKind::Fn(..)
697 | hir::ItemKind::Mod(..)
698 | hir::ItemKind::Static(..)
699 | hir::ItemKind::Struct(..)
700 | hir::ItemKind::Trait(..)
701 | hir::ItemKind::TraitAlias(..)
702 | hir::ItemKind::OpaqueTy(..)
703 | hir::ItemKind::TyAlias(..)
704 | hir::ItemKind::Union(..)
705 | hir::ItemKind::Use(..) => {
706 if item.vis.node.is_pub() {
714 // Update level of the item itself.
715 let item_level = self.update(item.hir_id, inherited_item_level);
717 // Update levels of nested things.
719 hir::ItemKind::Enum(ref def, _) => {
720 for variant in def.variants {
721 let variant_level = self.update(variant.id, item_level);
722 if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
723 self.update(ctor_hir_id, item_level);
725 for field in variant.data.fields() {
726 self.update(field.hir_id, variant_level);
730 hir::ItemKind::Impl(.., ref trait_ref, _, impl_item_refs) => {
731 for impl_item_ref in impl_item_refs {
732 if trait_ref.is_some() || impl_item_ref.vis.node.is_pub() {
733 self.update(impl_item_ref.id.hir_id, item_level);
737 hir::ItemKind::Trait(.., trait_item_refs) => {
738 for trait_item_ref in trait_item_refs {
739 self.update(trait_item_ref.id.hir_id, item_level);
742 hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => {
743 if let Some(ctor_hir_id) = def.ctor_hir_id() {
744 self.update(ctor_hir_id, item_level);
746 for field in def.fields() {
747 if field.vis.node.is_pub() {
748 self.update(field.hir_id, item_level);
752 hir::ItemKind::ForeignMod(ref foreign_mod) => {
753 for foreign_item in foreign_mod.items {
754 if foreign_item.vis.node.is_pub() {
755 self.update(foreign_item.hir_id, item_level);
759 hir::ItemKind::OpaqueTy(..)
760 | hir::ItemKind::Use(..)
761 | hir::ItemKind::Static(..)
762 | hir::ItemKind::Const(..)
763 | hir::ItemKind::GlobalAsm(..)
764 | hir::ItemKind::TyAlias(..)
765 | hir::ItemKind::Mod(..)
766 | hir::ItemKind::TraitAlias(..)
767 | hir::ItemKind::Fn(..)
768 | hir::ItemKind::ExternCrate(..) => {}
771 // Mark all items in interfaces of reachable items as reachable.
773 // The interface is empty.
774 hir::ItemKind::ExternCrate(..) => {}
775 // All nested items are checked by `visit_item`.
776 hir::ItemKind::Mod(..) => {}
777 // Re-exports are handled in `visit_mod`. However, in order to avoid looping over
778 // all of the items of a mod in `visit_mod` looking for use statements, we handle
779 // making sure that intermediate use statements have their visibilities updated here.
780 hir::ItemKind::Use(ref path, _) => {
781 if item_level.is_some() {
782 self.update_visibility_of_intermediate_use_statements(path.segments.as_ref());
785 // The interface is empty.
786 hir::ItemKind::GlobalAsm(..) => {}
787 hir::ItemKind::OpaqueTy(..) => {
788 // FIXME: This is some serious pessimization intended to workaround deficiencies
789 // in the reachability pass (`middle/reachable.rs`). Types are marked as link-time
790 // reachable if they are returned via `impl Trait`, even from private functions.
791 let exist_level = cmp::max(item_level, Some(AccessLevel::ReachableFromImplTrait));
792 self.reach(item.hir_id, exist_level).generics().predicates().ty();
795 hir::ItemKind::Const(..)
796 | hir::ItemKind::Static(..)
797 | hir::ItemKind::Fn(..)
798 | hir::ItemKind::TyAlias(..) => {
799 if item_level.is_some() {
800 self.reach(item.hir_id, item_level).generics().predicates().ty();
803 hir::ItemKind::Trait(.., trait_item_refs) => {
804 if item_level.is_some() {
805 self.reach(item.hir_id, item_level).generics().predicates();
807 for trait_item_ref in trait_item_refs {
808 let mut reach = self.reach(trait_item_ref.id.hir_id, item_level);
809 reach.generics().predicates();
811 if trait_item_ref.kind == AssocItemKind::Type
812 && !trait_item_ref.defaultness.has_value()
821 hir::ItemKind::TraitAlias(..) => {
822 if item_level.is_some() {
823 self.reach(item.hir_id, item_level).generics().predicates();
826 // Visit everything except for private impl items.
827 hir::ItemKind::Impl(.., impl_item_refs) => {
828 if item_level.is_some() {
829 self.reach(item.hir_id, item_level).generics().predicates().ty().trait_ref();
831 for impl_item_ref in impl_item_refs {
832 let impl_item_level = self.get(impl_item_ref.id.hir_id);
833 if impl_item_level.is_some() {
834 self.reach(impl_item_ref.id.hir_id, impl_item_level)
843 // Visit everything, but enum variants have their own levels.
844 hir::ItemKind::Enum(ref def, _) => {
845 if item_level.is_some() {
846 self.reach(item.hir_id, item_level).generics().predicates();
848 for variant in def.variants {
849 let variant_level = self.get(variant.id);
850 if variant_level.is_some() {
851 for field in variant.data.fields() {
852 self.reach(field.hir_id, variant_level).ty();
854 // Corner case: if the variant is reachable, but its
855 // enum is not, make the enum reachable as well.
856 self.update(item.hir_id, variant_level);
860 // Visit everything, but foreign items have their own levels.
861 hir::ItemKind::ForeignMod(ref foreign_mod) => {
862 for foreign_item in foreign_mod.items {
863 let foreign_item_level = self.get(foreign_item.hir_id);
864 if foreign_item_level.is_some() {
865 self.reach(foreign_item.hir_id, foreign_item_level)
872 // Visit everything except for private fields.
873 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
874 if item_level.is_some() {
875 self.reach(item.hir_id, item_level).generics().predicates();
876 for field in struct_def.fields() {
877 let field_level = self.get(field.hir_id);
878 if field_level.is_some() {
879 self.reach(field.hir_id, field_level).ty();
886 let orig_level = mem::replace(&mut self.prev_level, item_level);
887 intravisit::walk_item(self, item);
888 self.prev_level = orig_level;
891 fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
892 // Blocks can have public items, for example impls, but they always
893 // start as completely private regardless of publicity of a function,
894 // constant, type, field, etc., in which this block resides.
895 let orig_level = mem::replace(&mut self.prev_level, None);
896 intravisit::walk_block(self, b);
897 self.prev_level = orig_level;
900 fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, _sp: Span, id: hir::HirId) {
901 // This code is here instead of in visit_item so that the
902 // crate module gets processed as well.
903 if self.prev_level.is_some() {
904 let def_id = self.tcx.hir().local_def_id(id);
905 if let Some(exports) = self.tcx.module_exports(def_id) {
906 for export in exports.iter() {
907 if export.vis == ty::Visibility::Public {
908 if let Some(def_id) = export.res.opt_def_id() {
909 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
910 self.update(hir_id, Some(AccessLevel::Exported));
918 intravisit::walk_mod(self, m, id);
921 fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef<'tcx>) {
922 if attr::find_transparency(&md.attrs, md.legacy).0 != Transparency::Opaque {
923 self.update(md.hir_id, Some(AccessLevel::Public));
927 let macro_module_def_id =
928 ty::DefIdTree::parent(self.tcx, self.tcx.hir().local_def_id(md.hir_id)).unwrap();
929 let mut module_id = match self.tcx.hir().as_local_hir_id(macro_module_def_id) {
930 Some(module_id) if self.tcx.hir().is_hir_id_module(module_id) => module_id,
931 // `module_id` doesn't correspond to a `mod`, return early (#63164, #65252).
934 let level = if md.vis.node.is_pub() { self.get(module_id) } else { None };
935 let new_level = self.update(md.hir_id, level);
936 if new_level.is_none() {
941 let changed_reachability = self.update_macro_reachable(module_id, macro_module_def_id);
942 if changed_reachability || module_id == hir::CRATE_HIR_ID {
945 module_id = self.tcx.hir().get_parent_node(module_id);
950 impl ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
951 fn generics(&mut self) -> &mut Self {
952 for param in &self.ev.tcx.generics_of(self.item_def_id).params {
954 GenericParamDefKind::Lifetime => {}
955 GenericParamDefKind::Type { has_default, .. } => {
957 self.visit(self.ev.tcx.type_of(param.def_id));
960 GenericParamDefKind::Const => {
961 self.visit(self.ev.tcx.type_of(param.def_id));
968 fn predicates(&mut self) -> &mut Self {
969 self.visit_predicates(self.ev.tcx.predicates_of(self.item_def_id));
973 fn ty(&mut self) -> &mut Self {
974 self.visit(self.ev.tcx.type_of(self.item_def_id));
978 fn trait_ref(&mut self) -> &mut Self {
979 if let Some(trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) {
980 self.visit_trait(trait_ref);
986 impl DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
987 fn tcx(&self) -> TyCtxt<'tcx> {
990 fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) -> bool {
991 if let Some(hir_id) = self.ev.tcx.hir().as_local_hir_id(def_id) {
992 if let ((ty::Visibility::Public, ..), _)
993 | (_, Some(AccessLevel::ReachableFromImplTrait)) =
994 (def_id_visibility(self.tcx(), def_id), self.access_level)
996 self.ev.update(hir_id, self.access_level);
1003 //////////////////////////////////////////////////////////////////////////////////////
1004 /// Name privacy visitor, checks privacy and reports violations.
1005 /// Most of name privacy checks are performed during the main resolution phase,
1006 /// or later in type checking when field accesses and associated items are resolved.
1007 /// This pass performs remaining checks for fields in struct expressions and patterns.
1008 //////////////////////////////////////////////////////////////////////////////////////
1010 struct NamePrivacyVisitor<'a, 'tcx> {
1012 tables: &'a ty::TypeckTables<'tcx>,
1013 current_item: hir::HirId,
1014 empty_tables: &'a ty::TypeckTables<'tcx>,
1017 impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> {
1018 // Checks that a field in a struct constructor (expression or pattern) is accessible.
1021 use_ctxt: Span, // syntax context of the field name at the use site
1022 span: Span, // span of the field pattern, e.g., `x: 0`
1023 def: &'tcx ty::AdtDef, // definition of the struct or enum
1024 field: &'tcx ty::FieldDef,
1026 // definition of the field
1027 let ident = Ident::new(kw::Invalid, use_ctxt);
1028 let current_hir = self.current_item;
1029 let def_id = self.tcx.adjust_ident_and_get_scope(ident, def.did, current_hir).1;
1030 if !def.is_enum() && !field.vis.is_accessible_from(def_id, self.tcx) {
1035 "field `{}` of {} `{}` is private",
1037 def.variant_descr(),
1038 self.tcx.def_path_str(def.did)
1040 .span_label(span, format!("field `{}` is private", field.ident))
1046 impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> {
1047 type Map = Map<'tcx>;
1049 /// We want to visit items in the context of their containing
1050 /// module and so forth, so supply a crate for doing a deep walk.
1051 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
1052 NestedVisitorMap::All(&self.tcx.hir())
1055 fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) {
1056 // Don't visit nested modules, since we run a separate visitor walk
1057 // for each module in `privacy_access_levels`
1060 fn visit_nested_body(&mut self, body: hir::BodyId) {
1061 let orig_tables = mem::replace(&mut self.tables, self.tcx.body_tables(body));
1062 let body = self.tcx.hir().body(body);
1063 self.visit_body(body);
1064 self.tables = orig_tables;
1067 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1068 let orig_current_item = mem::replace(&mut self.current_item, item.hir_id);
1070 mem::replace(&mut self.tables, item_tables(self.tcx, item.hir_id, self.empty_tables));
1071 intravisit::walk_item(self, item);
1072 self.current_item = orig_current_item;
1073 self.tables = orig_tables;
1076 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
1078 mem::replace(&mut self.tables, item_tables(self.tcx, ti.hir_id, self.empty_tables));
1079 intravisit::walk_trait_item(self, ti);
1080 self.tables = orig_tables;
1083 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
1085 mem::replace(&mut self.tables, item_tables(self.tcx, ii.hir_id, self.empty_tables));
1086 intravisit::walk_impl_item(self, ii);
1087 self.tables = orig_tables;
1090 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1092 hir::ExprKind::Struct(ref qpath, fields, ref base) => {
1093 let res = self.tables.qpath_res(qpath, expr.hir_id);
1094 let adt = self.tables.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() {
1103 .find(|f| self.tcx.field_index(f.hir_id, self.tables) == 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);
1111 for field in fields {
1112 let use_ctxt = field.ident.span;
1113 let index = self.tcx.field_index(field.hir_id, self.tables);
1114 self.check_field(use_ctxt, field.span, adt, &variant.fields[index]);
1121 intravisit::walk_expr(self, expr);
1124 fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
1126 PatKind::Struct(ref qpath, fields, _) => {
1127 let res = self.tables.qpath_res(qpath, pat.hir_id);
1128 let adt = self.tables.pat_ty(pat).ty_adt_def().unwrap();
1129 let variant = adt.variant_of_res(res);
1130 for field in fields {
1131 let use_ctxt = field.ident.span;
1132 let index = self.tcx.field_index(field.hir_id, self.tables);
1133 self.check_field(use_ctxt, field.span, adt, &variant.fields[index]);
1139 intravisit::walk_pat(self, pat);
1143 ////////////////////////////////////////////////////////////////////////////////////////////
1144 /// Type privacy visitor, checks types for privacy and reports violations.
1145 /// Both explicitly written types and inferred types of expressions and patters are checked.
1146 /// Checks are performed on "semantic" types regardless of names and their hygiene.
1147 ////////////////////////////////////////////////////////////////////////////////////////////
1149 struct TypePrivacyVisitor<'a, 'tcx> {
1151 tables: &'a ty::TypeckTables<'tcx>,
1152 current_item: DefId,
1155 empty_tables: &'a ty::TypeckTables<'tcx>,
1158 impl<'a, 'tcx> TypePrivacyVisitor<'a, 'tcx> {
1159 fn item_is_accessible(&self, did: DefId) -> bool {
1160 def_id_visibility(self.tcx, did).0.is_accessible_from(self.current_item, self.tcx)
1163 // Take node-id of an expression or pattern and check its type for privacy.
1164 fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
1166 if self.visit(self.tables.node_type(id)) || self.visit(self.tables.node_substs(id)) {
1169 if let Some(adjustments) = self.tables.adjustments().get(id) {
1170 for adjustment in adjustments {
1171 if self.visit(adjustment.target) {
1179 fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1180 let is_error = !self.item_is_accessible(def_id);
1182 self.tcx.sess.span_err(self.span, &format!("{} `{}` is private", kind, descr));
1188 impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
1189 type Map = Map<'tcx>;
1191 /// We want to visit items in the context of their containing
1192 /// module and so forth, so supply a crate for doing a deep walk.
1193 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
1194 NestedVisitorMap::All(&self.tcx.hir())
1197 fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) {
1198 // Don't visit nested modules, since we run a separate visitor walk
1199 // for each module in `privacy_access_levels`
1202 fn visit_nested_body(&mut self, body: hir::BodyId) {
1203 let orig_tables = mem::replace(&mut self.tables, self.tcx.body_tables(body));
1204 let orig_in_body = mem::replace(&mut self.in_body, true);
1205 let body = self.tcx.hir().body(body);
1206 self.visit_body(body);
1207 self.tables = orig_tables;
1208 self.in_body = orig_in_body;
1211 fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) {
1212 self.span = hir_ty.span;
1215 if self.visit(self.tables.node_type(hir_ty.hir_id)) {
1219 // Types in signatures.
1220 // FIXME: This is very ineffective. Ideally each HIR type should be converted
1221 // into a semantic type only once and the result should be cached somehow.
1222 if self.visit(rustc_typeck::hir_ty_to_ty(self.tcx, hir_ty)) {
1227 intravisit::walk_ty(self, hir_ty);
1230 fn visit_trait_ref(&mut self, trait_ref: &'tcx hir::TraitRef<'tcx>) {
1231 self.span = trait_ref.path.span;
1233 // Avoid calling `hir_trait_to_predicates` in bodies, it will ICE.
1234 // The traits' privacy in bodies is already checked as a part of trait object types.
1235 let bounds = rustc_typeck::hir_trait_to_predicates(self.tcx, trait_ref);
1237 for (trait_predicate, _) in bounds.trait_bounds {
1238 if self.visit_trait(*trait_predicate.skip_binder()) {
1243 for (poly_predicate, _) in bounds.projection_bounds {
1245 if self.visit(poly_predicate.skip_binder().ty)
1246 || self.visit_trait(poly_predicate.skip_binder().projection_ty.trait_ref(tcx))
1253 intravisit::walk_trait_ref(self, trait_ref);
1256 // Check types of expressions
1257 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1258 if self.check_expr_pat_type(expr.hir_id, expr.span) {
1259 // Do not check nested expressions if the error already happened.
1263 hir::ExprKind::Assign(_, ref rhs, _) | hir::ExprKind::Match(ref rhs, ..) => {
1264 // Do not report duplicate errors for `x = y` and `match x { ... }`.
1265 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
1269 hir::ExprKind::MethodCall(_, span, _) => {
1270 // Method calls have to be checked specially.
1272 if let Some(def_id) = self.tables.type_dependent_def_id(expr.hir_id) {
1273 if self.visit(self.tcx.type_of(def_id)) {
1279 .delay_span_bug(expr.span, "no type-dependent def for method call");
1285 intravisit::walk_expr(self, expr);
1288 // Prohibit access to associated items with insufficient nominal visibility.
1290 // Additionally, until better reachability analysis for macros 2.0 is available,
1291 // we prohibit access to private statics from other crates, this allows to give
1292 // more code internal visibility at link time. (Access to private functions
1293 // is already prohibited by type privacy for function types.)
1294 fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) {
1295 let def = match self.tables.qpath_res(qpath, id) {
1296 Res::Def(kind, def_id) => Some((kind, def_id)),
1299 let def = def.filter(|(kind, _)| match kind {
1301 | DefKind::AssocConst
1303 | DefKind::AssocOpaqueTy
1304 | DefKind::Static => true,
1307 if let Some((kind, def_id)) = def {
1308 let is_local_static =
1309 if let DefKind::Static = kind { def_id.is_local() } else { false };
1310 if !self.item_is_accessible(def_id) && !is_local_static {
1311 let name = match *qpath {
1312 hir::QPath::Resolved(_, ref path) => path.to_string(),
1313 hir::QPath::TypeRelative(_, ref segment) => segment.ident.to_string(),
1315 let msg = format!("{} `{}` is private", kind.descr(def_id), name);
1316 self.tcx.sess.span_err(span, &msg);
1321 intravisit::walk_qpath(self, qpath, id, span);
1324 // Check types of patterns.
1325 fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) {
1326 if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
1327 // Do not check nested patterns if the error already happened.
1331 intravisit::walk_pat(self, pattern);
1334 fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) {
1335 if let Some(ref init) = local.init {
1336 if self.check_expr_pat_type(init.hir_id, init.span) {
1337 // Do not report duplicate errors for `let x = y`.
1342 intravisit::walk_local(self, local);
1345 // Check types in item interfaces.
1346 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1347 let orig_current_item =
1348 mem::replace(&mut self.current_item, self.tcx.hir().local_def_id(item.hir_id));
1349 let orig_in_body = mem::replace(&mut self.in_body, false);
1351 mem::replace(&mut self.tables, item_tables(self.tcx, item.hir_id, self.empty_tables));
1352 intravisit::walk_item(self, item);
1353 self.tables = orig_tables;
1354 self.in_body = orig_in_body;
1355 self.current_item = orig_current_item;
1358 fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) {
1360 mem::replace(&mut self.tables, item_tables(self.tcx, ti.hir_id, self.empty_tables));
1361 intravisit::walk_trait_item(self, ti);
1362 self.tables = orig_tables;
1365 fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) {
1367 mem::replace(&mut self.tables, item_tables(self.tcx, ii.hir_id, self.empty_tables));
1368 intravisit::walk_impl_item(self, ii);
1369 self.tables = orig_tables;
1373 impl DefIdVisitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
1374 fn tcx(&self) -> TyCtxt<'tcx> {
1377 fn visit_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1378 self.check_def_id(def_id, kind, descr)
1382 ///////////////////////////////////////////////////////////////////////////////
1383 /// Obsolete visitors for checking for private items in public interfaces.
1384 /// These visitors are supposed to be kept in frozen state and produce an
1385 /// "old error node set". For backward compatibility the new visitor reports
1386 /// warnings instead of hard errors when the erroneous node is not in this old set.
1387 ///////////////////////////////////////////////////////////////////////////////
1389 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1391 access_levels: &'a AccessLevels,
1393 // Set of errors produced by this obsolete visitor.
1394 old_error_set: HirIdSet,
1397 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1398 inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
1399 /// Whether the type refers to private types.
1400 contains_private: bool,
1401 /// Whether we've recurred at all (i.e., if we're pointing at the
1402 /// first type on which `visit_ty` was called).
1403 at_outer_type: bool,
1404 /// Whether that first type is a public path.
1405 outer_type_is_public_path: bool,
1408 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1409 fn path_is_private_type(&self, path: &hir::Path<'_>) -> bool {
1410 let did = match path.res {
1411 Res::PrimTy(..) | Res::SelfTy(..) | Res::Err => return false,
1412 res => res.def_id(),
1415 // A path can only be private if:
1416 // it's in this crate...
1417 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(did) {
1418 // .. and it corresponds to a private type in the AST (this returns
1419 // `None` for type parameters).
1420 match self.tcx.hir().find(hir_id) {
1421 Some(Node::Item(ref item)) => !item.vis.node.is_pub(),
1422 Some(_) | None => false,
1429 fn trait_is_public(&self, trait_id: hir::HirId) -> bool {
1430 // FIXME: this would preferably be using `exported_items`, but all
1431 // traits are exported currently (see `EmbargoVisitor.exported_trait`).
1432 self.access_levels.is_public(trait_id)
1435 fn check_generic_bound(&mut self, bound: &hir::GenericBound<'_>) {
1436 if let hir::GenericBound::Trait(ref trait_ref, _) = *bound {
1437 if self.path_is_private_type(&trait_ref.trait_ref.path) {
1438 self.old_error_set.insert(trait_ref.trait_ref.hir_ref_id);
1443 fn item_is_public(&self, id: &hir::HirId, vis: &hir::Visibility<'_>) -> bool {
1444 self.access_levels.is_reachable(*id) || vis.node.is_pub()
1448 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1451 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
1452 NestedVisitorMap::None
1455 fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
1456 if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = ty.kind {
1457 if self.inner.path_is_private_type(path) {
1458 self.contains_private = true;
1459 // Found what we're looking for, so let's stop working.
1463 if let hir::TyKind::Path(_) = ty.kind {
1464 if self.at_outer_type {
1465 self.outer_type_is_public_path = true;
1468 self.at_outer_type = false;
1469 intravisit::walk_ty(self, ty)
1472 // Don't want to recurse into `[, .. expr]`.
1473 fn visit_expr(&mut self, _: &hir::Expr<'_>) {}
1476 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1477 type Map = Map<'tcx>;
1479 /// We want to visit items in the context of their containing
1480 /// module and so forth, so supply a crate for doing a deep walk.
1481 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
1482 NestedVisitorMap::All(&self.tcx.hir())
1485 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1487 // Contents of a private mod can be re-exported, so we need
1488 // to check internals.
1489 hir::ItemKind::Mod(_) => {}
1491 // An `extern {}` doesn't introduce a new privacy
1492 // namespace (the contents have their own privacies).
1493 hir::ItemKind::ForeignMod(_) => {}
1495 hir::ItemKind::Trait(.., ref bounds, _) => {
1496 if !self.trait_is_public(item.hir_id) {
1500 for bound in bounds.iter() {
1501 self.check_generic_bound(bound)
1505 // Impls need some special handling to try to offer useful
1506 // error messages without (too many) false positives
1507 // (i.e., we could just return here to not check them at
1508 // all, or some worse estimation of whether an impl is
1509 // publicly visible).
1510 hir::ItemKind::Impl(.., ref g, ref trait_ref, ref self_, impl_item_refs) => {
1511 // `impl [... for] Private` is never visible.
1512 let self_contains_private;
1513 // `impl [... for] Public<...>`, but not `impl [... for]
1514 // Vec<Public>` or `(Public,)`, etc.
1515 let self_is_public_path;
1517 // Check the properties of the `Self` type:
1519 let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
1521 contains_private: false,
1522 at_outer_type: true,
1523 outer_type_is_public_path: false,
1525 visitor.visit_ty(&self_);
1526 self_contains_private = visitor.contains_private;
1527 self_is_public_path = visitor.outer_type_is_public_path;
1530 // Miscellaneous info about the impl:
1532 // `true` iff this is `impl Private for ...`.
1533 let not_private_trait = trait_ref.as_ref().map_or(
1534 true, // no trait counts as public trait
1536 let did = tr.path.res.def_id();
1538 if let Some(hir_id) = self.tcx.hir().as_local_hir_id(did) {
1539 self.trait_is_public(hir_id)
1541 true // external traits must be public
1546 // `true` iff this is a trait impl or at least one method is public.
1548 // `impl Public { $( fn ...() {} )* }` is not visible.
1550 // This is required over just using the methods' privacy
1551 // directly because we might have `impl<T: Foo<Private>> ...`,
1552 // and we shouldn't warn about the generics if all the methods
1553 // are private (because `T` won't be visible externally).
1554 let trait_or_some_public_method = trait_ref.is_some()
1555 || impl_item_refs.iter().any(|impl_item_ref| {
1556 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1557 match impl_item.kind {
1558 hir::ImplItemKind::Const(..) | hir::ImplItemKind::Method(..) => {
1559 self.access_levels.is_reachable(impl_item_ref.id.hir_id)
1561 hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(_) => {
1567 if !self_contains_private && not_private_trait && trait_or_some_public_method {
1568 intravisit::walk_generics(self, g);
1572 for impl_item_ref in impl_item_refs {
1573 // This is where we choose whether to walk down
1574 // further into the impl to check its items. We
1575 // should only walk into public items so that we
1576 // don't erroneously report errors for private
1577 // types in private items.
1578 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1579 match impl_item.kind {
1580 hir::ImplItemKind::Const(..)
1581 | hir::ImplItemKind::Method(..)
1583 .item_is_public(&impl_item.hir_id, &impl_item.vis) =>
1585 intravisit::walk_impl_item(self, impl_item)
1587 hir::ImplItemKind::TyAlias(..) => {
1588 intravisit::walk_impl_item(self, impl_item)
1595 // Any private types in a trait impl fall into three
1597 // 1. mentioned in the trait definition
1598 // 2. mentioned in the type params/generics
1599 // 3. mentioned in the associated types of the impl
1601 // Those in 1. can only occur if the trait is in
1602 // this crate and will've been warned about on the
1603 // trait definition (there's no need to warn twice
1604 // so we don't check the methods).
1606 // Those in 2. are warned via walk_generics and this
1608 intravisit::walk_path(self, &tr.path);
1610 // Those in 3. are warned with this call.
1611 for impl_item_ref in impl_item_refs {
1612 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1613 if let hir::ImplItemKind::TyAlias(ref ty) = impl_item.kind {
1619 } else if trait_ref.is_none() && self_is_public_path {
1620 // `impl Public<Private> { ... }`. Any public static
1621 // methods will be visible as `Public::foo`.
1622 let mut found_pub_static = false;
1623 for impl_item_ref in impl_item_refs {
1624 if self.item_is_public(&impl_item_ref.id.hir_id, &impl_item_ref.vis) {
1625 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1626 match impl_item_ref.kind {
1627 AssocItemKind::Const => {
1628 found_pub_static = true;
1629 intravisit::walk_impl_item(self, impl_item);
1631 AssocItemKind::Method { has_self: false } => {
1632 found_pub_static = true;
1633 intravisit::walk_impl_item(self, impl_item);
1639 if found_pub_static {
1640 intravisit::walk_generics(self, g)
1646 // `type ... = ...;` can contain private types, because
1647 // we're introducing a new name.
1648 hir::ItemKind::TyAlias(..) => return,
1650 // Not at all public, so we don't care.
1651 _ if !self.item_is_public(&item.hir_id, &item.vis) => {
1658 // We've carefully constructed it so that if we're here, then
1659 // any `visit_ty`'s will be called on things that are in
1660 // public signatures, i.e., things that we're interested in for
1662 intravisit::walk_item(self, item);
1665 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1666 for param in generics.params {
1667 for bound in param.bounds {
1668 self.check_generic_bound(bound);
1671 for predicate in generics.where_clause.predicates {
1673 hir::WherePredicate::BoundPredicate(bound_pred) => {
1674 for bound in bound_pred.bounds.iter() {
1675 self.check_generic_bound(bound)
1678 hir::WherePredicate::RegionPredicate(_) => {}
1679 hir::WherePredicate::EqPredicate(eq_pred) => {
1680 self.visit_ty(&eq_pred.rhs_ty);
1686 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
1687 if self.access_levels.is_reachable(item.hir_id) {
1688 intravisit::walk_foreign_item(self, item)
1692 fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
1693 if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = t.kind {
1694 if self.path_is_private_type(path) {
1695 self.old_error_set.insert(t.hir_id);
1698 intravisit::walk_ty(self, t)
1703 v: &'tcx hir::Variant<'tcx>,
1704 g: &'tcx hir::Generics<'tcx>,
1705 item_id: hir::HirId,
1707 if self.access_levels.is_reachable(v.id) {
1708 self.in_variant = true;
1709 intravisit::walk_variant(self, v, g, item_id);
1710 self.in_variant = false;
1714 fn visit_struct_field(&mut self, s: &'tcx hir::StructField<'tcx>) {
1715 if s.vis.node.is_pub() || self.in_variant {
1716 intravisit::walk_struct_field(self, s);
1720 // We don't need to introspect into these at all: an
1721 // expression/block context can't possibly contain exported things.
1722 // (Making them no-ops stops us from traversing the whole AST without
1723 // having to be super careful about our `walk_...` calls above.)
1724 fn visit_block(&mut self, _: &'tcx hir::Block<'tcx>) {}
1725 fn visit_expr(&mut self, _: &'tcx hir::Expr<'tcx>) {}
1728 ///////////////////////////////////////////////////////////////////////////////
1729 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1730 /// finds any private components in it.
1731 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1732 /// and traits in public interfaces.
1733 ///////////////////////////////////////////////////////////////////////////////
1735 struct SearchInterfaceForPrivateItemsVisitor<'tcx> {
1737 item_id: hir::HirId,
1740 /// The visitor checks that each component type is at least this visible.
1741 required_visibility: ty::Visibility,
1742 has_pub_restricted: bool,
1743 has_old_errors: bool,
1747 impl SearchInterfaceForPrivateItemsVisitor<'tcx> {
1748 fn generics(&mut self) -> &mut Self {
1749 for param in &self.tcx.generics_of(self.item_def_id).params {
1751 GenericParamDefKind::Lifetime => {}
1752 GenericParamDefKind::Type { has_default, .. } => {
1754 self.visit(self.tcx.type_of(param.def_id));
1757 GenericParamDefKind::Const => {
1758 self.visit(self.tcx.type_of(param.def_id));
1765 fn predicates(&mut self) -> &mut Self {
1766 // N.B., we use `explicit_predicates_of` and not `predicates_of`
1767 // because we don't want to report privacy errors due to where
1768 // clauses that the compiler inferred. We only want to
1769 // consider the ones that the user wrote. This is important
1770 // for the inferred outlives rules; see
1771 // `src/test/ui/rfc-2093-infer-outlives/privacy.rs`.
1772 self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id));
1776 fn ty(&mut self) -> &mut Self {
1777 self.visit(self.tcx.type_of(self.item_def_id));
1781 fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1782 if self.leaks_private_dep(def_id) {
1784 lint::builtin::EXPORTED_PRIVATE_DEPENDENCIES,
1788 "{} `{}` from private dependency '{}' in public \
1792 self.tcx.crate_name(def_id.krate)
1797 let hir_id = match self.tcx.hir().as_local_hir_id(def_id) {
1798 Some(hir_id) => hir_id,
1799 None => return false,
1802 let (vis, vis_span, vis_descr) = def_id_visibility(self.tcx, def_id);
1803 if !vis.is_at_least(self.required_visibility, self.tcx) {
1804 let msg = format!("{} {} `{}` in public interface", vis_descr, kind, descr);
1805 if self.has_pub_restricted || self.has_old_errors || self.in_assoc_ty {
1806 let mut err = if kind == "trait" {
1807 struct_span_err!(self.tcx.sess, self.span, E0445, "{}", msg)
1809 struct_span_err!(self.tcx.sess, self.span, E0446, "{}", msg)
1811 err.span_label(self.span, format!("can't leak {} {}", vis_descr, kind));
1812 err.span_label(vis_span, format!("`{}` declared as {}", descr, vis_descr));
1815 let err_code = if kind == "trait" { "E0445" } else { "E0446" };
1817 lint::builtin::PRIVATE_IN_PUBLIC,
1820 &format!("{} (error {})", msg, err_code),
1828 /// An item is 'leaked' from a private dependency if all
1829 /// of the following are true:
1830 /// 1. It's contained within a public type
1831 /// 2. It comes from a private crate
1832 fn leaks_private_dep(&self, item_id: DefId) -> bool {
1833 let ret = self.required_visibility == ty::Visibility::Public
1834 && self.tcx.is_private_dep(item_id.krate);
1836 log::debug!("leaks_private_dep(item_id={:?})={}", item_id, ret);
1841 impl DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> {
1842 fn tcx(&self) -> TyCtxt<'tcx> {
1845 fn visit_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1846 self.check_def_id(def_id, kind, descr)
1850 struct PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1852 has_pub_restricted: bool,
1853 old_error_set: &'a HirIdSet,
1856 impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1859 item_id: hir::HirId,
1860 required_visibility: ty::Visibility,
1861 ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> {
1862 let mut has_old_errors = false;
1864 // Slow path taken only if there any errors in the crate.
1865 for &id in self.old_error_set {
1866 // Walk up the nodes until we find `item_id` (or we hit a root).
1870 has_old_errors = true;
1873 let parent = self.tcx.hir().get_parent_node(id);
1885 SearchInterfaceForPrivateItemsVisitor {
1888 item_def_id: self.tcx.hir().local_def_id(item_id),
1889 span: self.tcx.hir().span(item_id),
1890 required_visibility,
1891 has_pub_restricted: self.has_pub_restricted,
1897 fn check_assoc_item(
1900 assoc_item_kind: AssocItemKind,
1901 defaultness: hir::Defaultness,
1902 vis: ty::Visibility,
1904 let mut check = self.check(hir_id, vis);
1906 let (check_ty, is_assoc_ty) = match assoc_item_kind {
1907 AssocItemKind::Const | AssocItemKind::Method { .. } => (true, false),
1908 AssocItemKind::Type => (defaultness.has_value(), true),
1909 // `ty()` for opaque types is the underlying type,
1910 // it's not a part of interface, so we skip it.
1911 AssocItemKind::OpaqueTy => (false, true),
1913 check.in_assoc_ty = is_assoc_ty;
1914 check.generics().predicates();
1921 impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1922 type Map = Map<'tcx>;
1924 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
1925 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
1928 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1930 let item_visibility = ty::Visibility::from_hir(&item.vis, item.hir_id, tcx);
1933 // Crates are always public.
1934 hir::ItemKind::ExternCrate(..) => {}
1935 // All nested items are checked by `visit_item`.
1936 hir::ItemKind::Mod(..) => {}
1937 // Checked in resolve.
1938 hir::ItemKind::Use(..) => {}
1940 hir::ItemKind::GlobalAsm(..) => {}
1941 // Subitems of these items have inherited publicity.
1942 hir::ItemKind::Const(..)
1943 | hir::ItemKind::Static(..)
1944 | hir::ItemKind::Fn(..)
1945 | hir::ItemKind::TyAlias(..) => {
1946 self.check(item.hir_id, item_visibility).generics().predicates().ty();
1948 hir::ItemKind::OpaqueTy(..) => {
1949 // `ty()` for opaque types is the underlying type,
1950 // it's not a part of interface, so we skip it.
1951 self.check(item.hir_id, item_visibility).generics().predicates();
1953 hir::ItemKind::Trait(.., trait_item_refs) => {
1954 self.check(item.hir_id, item_visibility).generics().predicates();
1956 for trait_item_ref in trait_item_refs {
1957 self.check_assoc_item(
1958 trait_item_ref.id.hir_id,
1959 trait_item_ref.kind,
1960 trait_item_ref.defaultness,
1965 hir::ItemKind::TraitAlias(..) => {
1966 self.check(item.hir_id, item_visibility).generics().predicates();
1968 hir::ItemKind::Enum(ref def, _) => {
1969 self.check(item.hir_id, item_visibility).generics().predicates();
1971 for variant in def.variants {
1972 for field in variant.data.fields() {
1973 self.check(field.hir_id, item_visibility).ty();
1977 // Subitems of foreign modules have their own publicity.
1978 hir::ItemKind::ForeignMod(ref foreign_mod) => {
1979 for foreign_item in foreign_mod.items {
1980 let vis = ty::Visibility::from_hir(&foreign_item.vis, item.hir_id, tcx);
1981 self.check(foreign_item.hir_id, vis).generics().predicates().ty();
1984 // Subitems of structs and unions have their own publicity.
1985 hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
1986 self.check(item.hir_id, item_visibility).generics().predicates();
1988 for field in struct_def.fields() {
1989 let field_visibility = ty::Visibility::from_hir(&field.vis, item.hir_id, tcx);
1990 self.check(field.hir_id, min(item_visibility, field_visibility, tcx)).ty();
1993 // An inherent impl is public when its type is public
1994 // Subitems of inherent impls have their own publicity.
1995 // A trait impl is public when both its type and its trait are public
1996 // Subitems of trait impls have inherited publicity.
1997 hir::ItemKind::Impl(.., ref trait_ref, _, impl_item_refs) => {
1998 let impl_vis = ty::Visibility::of_impl(item.hir_id, tcx, &Default::default());
1999 self.check(item.hir_id, impl_vis).generics().predicates();
2000 for impl_item_ref in impl_item_refs {
2001 let impl_item = tcx.hir().impl_item(impl_item_ref.id);
2002 let impl_item_vis = if trait_ref.is_none() {
2004 ty::Visibility::from_hir(&impl_item.vis, item.hir_id, tcx),
2011 self.check_assoc_item(
2012 impl_item_ref.id.hir_id,
2014 impl_item_ref.defaultness,
2023 pub fn provide(providers: &mut Providers<'_>) {
2024 *providers = Providers {
2025 privacy_access_levels,
2026 check_private_in_public,
2032 fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: DefId) {
2033 let empty_tables = ty::TypeckTables::empty(None);
2035 // Check privacy of names not checked in previous compilation stages.
2036 let mut visitor = NamePrivacyVisitor {
2038 tables: &empty_tables,
2039 current_item: hir::DUMMY_HIR_ID,
2040 empty_tables: &empty_tables,
2042 let (module, span, hir_id) = tcx.hir().get_module(module_def_id);
2044 intravisit::walk_mod(&mut visitor, module, hir_id);
2046 // Check privacy of explicitly written types and traits as well as
2047 // inferred types of expressions and patterns.
2048 let mut visitor = TypePrivacyVisitor {
2050 tables: &empty_tables,
2051 current_item: module_def_id,
2054 empty_tables: &empty_tables,
2056 intravisit::walk_mod(&mut visitor, module, hir_id);
2059 fn privacy_access_levels(tcx: TyCtxt<'_>, krate: CrateNum) -> &AccessLevels {
2060 assert_eq!(krate, LOCAL_CRATE);
2062 // Build up a set of all exported items in the AST. This is a set of all
2063 // items which are reachable from external crates based on visibility.
2064 let mut visitor = EmbargoVisitor {
2066 access_levels: Default::default(),
2067 macro_reachable: Default::default(),
2068 prev_level: Some(AccessLevel::Public),
2072 intravisit::walk_crate(&mut visitor, tcx.hir().krate());
2073 if visitor.changed {
2074 visitor.changed = false;
2079 visitor.update(hir::CRATE_HIR_ID, Some(AccessLevel::Public));
2081 tcx.arena.alloc(visitor.access_levels)
2084 fn check_private_in_public(tcx: TyCtxt<'_>, krate: CrateNum) {
2085 assert_eq!(krate, LOCAL_CRATE);
2087 let access_levels = tcx.privacy_access_levels(LOCAL_CRATE);
2089 let krate = tcx.hir().krate();
2091 let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
2093 access_levels: &access_levels,
2095 old_error_set: Default::default(),
2097 intravisit::walk_crate(&mut visitor, krate);
2099 let has_pub_restricted = {
2100 let mut pub_restricted_visitor = PubRestrictedVisitor { tcx, has_pub_restricted: false };
2101 intravisit::walk_crate(&mut pub_restricted_visitor, krate);
2102 pub_restricted_visitor.has_pub_restricted
2105 // Check for private types and traits in public interfaces.
2106 let mut visitor = PrivateItemsInPublicInterfacesVisitor {
2109 old_error_set: &visitor.old_error_set,
2111 krate.visit_all_item_likes(&mut DeepVisitor::new(&mut visitor));