]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_privacy/src/lib.rs
privacy: port unnamed "item is private" diag
[rust.git] / compiler / rustc_privacy / src / lib.rs
1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
2 #![feature(control_flow_enum)]
3 #![feature(try_blocks)]
4 #![feature(associated_type_defaults)]
5 #![recursion_limit = "256"]
6 #![allow(rustc::potential_query_instability)]
7
8 mod errors;
9
10 use rustc_ast::MacroDef;
11 use rustc_attr as attr;
12 use rustc_data_structures::fx::FxHashSet;
13 use rustc_data_structures::intern::Interned;
14 use rustc_errors::struct_span_err;
15 use rustc_hir as hir;
16 use rustc_hir::def::{DefKind, Res};
17 use rustc_hir::def_id::{DefId, LocalDefId, LocalDefIdSet, CRATE_DEF_ID};
18 use rustc_hir::intravisit::{self, Visitor};
19 use rustc_hir::{AssocItemKind, HirIdSet, ItemId, Node, PatKind};
20 use rustc_middle::bug;
21 use rustc_middle::hir::nested_filter;
22 use rustc_middle::middle::privacy::{AccessLevel, AccessLevels};
23 use rustc_middle::span_bug;
24 use rustc_middle::thir::abstract_const::Node as ACNode;
25 use rustc_middle::ty::query::Providers;
26 use rustc_middle::ty::subst::InternalSubsts;
27 use rustc_middle::ty::{self, Const, DefIdTree, GenericParamDefKind};
28 use rustc_middle::ty::{TraitRef, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable, TypeVisitor};
29 use rustc_session::lint;
30 use rustc_span::hygiene::Transparency;
31 use rustc_span::symbol::{kw, Ident};
32 use rustc_span::Span;
33 use rustc_trait_selection::traits::const_evaluatable::{self, AbstractConst};
34
35 use std::marker::PhantomData;
36 use std::ops::ControlFlow;
37 use std::{cmp, fmt, mem};
38
39 use errors::{FieldIsPrivate, FieldIsPrivateLabel, ItemIsPrivate, UnnamedItemIsPrivate};
40
41 ////////////////////////////////////////////////////////////////////////////////
42 /// Generic infrastructure used to implement specific visitors below.
43 ////////////////////////////////////////////////////////////////////////////////
44
45 /// Implemented to visit all `DefId`s in a type.
46 /// Visiting `DefId`s is useful because visibilities and reachabilities are attached to them.
47 /// The idea is to visit "all components of a type", as documented in
48 /// <https://github.com/rust-lang/rfcs/blob/master/text/2145-type-privacy.md#how-to-determine-visibility-of-a-type>.
49 /// The default type visitor (`TypeVisitor`) does most of the job, but it has some shortcomings.
50 /// First, it doesn't have overridable `fn visit_trait_ref`, so we have to catch trait `DefId`s
51 /// manually. Second, it doesn't visit some type components like signatures of fn types, or traits
52 /// in `impl Trait`, see individual comments in `DefIdVisitorSkeleton::visit_ty`.
53 trait DefIdVisitor<'tcx> {
54     type BreakTy = ();
55
56     fn tcx(&self) -> TyCtxt<'tcx>;
57     fn shallow(&self) -> bool {
58         false
59     }
60     fn skip_assoc_tys(&self) -> bool {
61         false
62     }
63     fn visit_def_id(
64         &mut self,
65         def_id: DefId,
66         kind: &str,
67         descr: &dyn fmt::Display,
68     ) -> ControlFlow<Self::BreakTy>;
69
70     /// Not overridden, but used to actually visit types and traits.
71     fn skeleton(&mut self) -> DefIdVisitorSkeleton<'_, 'tcx, Self> {
72         DefIdVisitorSkeleton {
73             def_id_visitor: self,
74             visited_opaque_tys: Default::default(),
75             dummy: Default::default(),
76         }
77     }
78     fn visit(&mut self, ty_fragment: impl TypeFoldable<'tcx>) -> ControlFlow<Self::BreakTy> {
79         ty_fragment.visit_with(&mut self.skeleton())
80     }
81     fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> ControlFlow<Self::BreakTy> {
82         self.skeleton().visit_trait(trait_ref)
83     }
84     fn visit_projection_ty(
85         &mut self,
86         projection: ty::ProjectionTy<'tcx>,
87     ) -> ControlFlow<Self::BreakTy> {
88         self.skeleton().visit_projection_ty(projection)
89     }
90     fn visit_predicates(
91         &mut self,
92         predicates: ty::GenericPredicates<'tcx>,
93     ) -> ControlFlow<Self::BreakTy> {
94         self.skeleton().visit_predicates(predicates)
95     }
96 }
97
98 struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> {
99     def_id_visitor: &'v mut V,
100     visited_opaque_tys: FxHashSet<DefId>,
101     dummy: PhantomData<TyCtxt<'tcx>>,
102 }
103
104 impl<'tcx, V> DefIdVisitorSkeleton<'_, 'tcx, V>
105 where
106     V: DefIdVisitor<'tcx> + ?Sized,
107 {
108     fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> ControlFlow<V::BreakTy> {
109         let TraitRef { def_id, substs } = trait_ref;
110         self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref.print_only_trait_path())?;
111         if self.def_id_visitor.shallow() { ControlFlow::CONTINUE } else { substs.visit_with(self) }
112     }
113
114     fn visit_projection_ty(
115         &mut self,
116         projection: ty::ProjectionTy<'tcx>,
117     ) -> ControlFlow<V::BreakTy> {
118         let (trait_ref, assoc_substs) =
119             projection.trait_ref_and_own_substs(self.def_id_visitor.tcx());
120         self.visit_trait(trait_ref)?;
121         if self.def_id_visitor.shallow() {
122             ControlFlow::CONTINUE
123         } else {
124             assoc_substs.iter().try_for_each(|subst| subst.visit_with(self))
125         }
126     }
127
128     fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<V::BreakTy> {
129         match predicate.kind().skip_binder() {
130             ty::PredicateKind::Trait(ty::TraitPredicate {
131                 trait_ref,
132                 constness: _,
133                 polarity: _,
134             }) => self.visit_trait(trait_ref),
135             ty::PredicateKind::Projection(ty::ProjectionPredicate { projection_ty, term }) => {
136                 term.visit_with(self)?;
137                 self.visit_projection_ty(projection_ty)
138             }
139             ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _region)) => {
140                 ty.visit_with(self)
141             }
142             ty::PredicateKind::RegionOutlives(..) => ControlFlow::CONTINUE,
143             ty::PredicateKind::ConstEvaluatable(uv)
144                 if self.def_id_visitor.tcx().features().generic_const_exprs =>
145             {
146                 let tcx = self.def_id_visitor.tcx();
147                 if let Ok(Some(ct)) = AbstractConst::new(tcx, uv) {
148                     self.visit_abstract_const_expr(tcx, ct)?;
149                 }
150                 ControlFlow::CONTINUE
151             }
152             _ => bug!("unexpected predicate: {:?}", predicate),
153         }
154     }
155
156     fn visit_abstract_const_expr(
157         &mut self,
158         tcx: TyCtxt<'tcx>,
159         ct: AbstractConst<'tcx>,
160     ) -> ControlFlow<V::BreakTy> {
161         const_evaluatable::walk_abstract_const(tcx, ct, |node| match node.root(tcx) {
162             ACNode::Leaf(leaf) => self.visit_const(leaf),
163             ACNode::Cast(_, _, ty) => self.visit_ty(ty),
164             ACNode::Binop(..) | ACNode::UnaryOp(..) | ACNode::FunctionCall(_, _) => {
165                 ControlFlow::CONTINUE
166             }
167         })
168     }
169
170     fn visit_predicates(
171         &mut self,
172         predicates: ty::GenericPredicates<'tcx>,
173     ) -> ControlFlow<V::BreakTy> {
174         let ty::GenericPredicates { parent: _, predicates } = predicates;
175         predicates.iter().try_for_each(|&(predicate, _span)| self.visit_predicate(predicate))
176     }
177 }
178
179 impl<'tcx, V> TypeVisitor<'tcx> for DefIdVisitorSkeleton<'_, 'tcx, V>
180 where
181     V: DefIdVisitor<'tcx> + ?Sized,
182 {
183     type BreakTy = V::BreakTy;
184
185     fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<V::BreakTy> {
186         let tcx = self.def_id_visitor.tcx();
187         // InternalSubsts are not visited here because they are visited below
188         // in `super_visit_with`.
189         match *ty.kind() {
190             ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), ..)
191             | ty::Foreign(def_id)
192             | ty::FnDef(def_id, ..)
193             | ty::Closure(def_id, ..)
194             | ty::Generator(def_id, ..) => {
195                 self.def_id_visitor.visit_def_id(def_id, "type", &ty)?;
196                 if self.def_id_visitor.shallow() {
197                     return ControlFlow::CONTINUE;
198                 }
199                 // Default type visitor doesn't visit signatures of fn types.
200                 // Something like `fn() -> Priv {my_func}` is considered a private type even if
201                 // `my_func` is public, so we need to visit signatures.
202                 if let ty::FnDef(..) = ty.kind() {
203                     tcx.fn_sig(def_id).visit_with(self)?;
204                 }
205                 // Inherent static methods don't have self type in substs.
206                 // Something like `fn() {my_method}` type of the method
207                 // `impl Pub<Priv> { pub fn my_method() {} }` is considered a private type,
208                 // so we need to visit the self type additionally.
209                 if let Some(assoc_item) = tcx.opt_associated_item(def_id) {
210                     if let ty::ImplContainer(impl_def_id) = assoc_item.container {
211                         tcx.type_of(impl_def_id).visit_with(self)?;
212                     }
213                 }
214             }
215             ty::Projection(proj) => {
216                 if self.def_id_visitor.skip_assoc_tys() {
217                     // Visitors searching for minimal visibility/reachability want to
218                     // conservatively approximate associated types like `<Type as Trait>::Alias`
219                     // as visible/reachable even if both `Type` and `Trait` are private.
220                     // Ideally, associated types should be substituted in the same way as
221                     // free type aliases, but this isn't done yet.
222                     return ControlFlow::CONTINUE;
223                 }
224                 // This will also visit substs if necessary, so we don't need to recurse.
225                 return self.visit_projection_ty(proj);
226             }
227             ty::Dynamic(predicates, ..) => {
228                 // All traits in the list are considered the "primary" part of the type
229                 // and are visited by shallow visitors.
230                 for predicate in predicates {
231                     let trait_ref = match predicate.skip_binder() {
232                         ty::ExistentialPredicate::Trait(trait_ref) => trait_ref,
233                         ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx),
234                         ty::ExistentialPredicate::AutoTrait(def_id) => {
235                             ty::ExistentialTraitRef { def_id, substs: InternalSubsts::empty() }
236                         }
237                     };
238                     let ty::ExistentialTraitRef { def_id, substs: _ } = trait_ref;
239                     self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref)?;
240                 }
241             }
242             ty::Opaque(def_id, ..) => {
243                 // Skip repeated `Opaque`s to avoid infinite recursion.
244                 if self.visited_opaque_tys.insert(def_id) {
245                     // The intent is to treat `impl Trait1 + Trait2` identically to
246                     // `dyn Trait1 + Trait2`. Therefore we ignore def-id of the opaque type itself
247                     // (it either has no visibility, or its visibility is insignificant, like
248                     // visibilities of type aliases) and recurse into bounds instead to go
249                     // through the trait list (default type visitor doesn't visit those traits).
250                     // All traits in the list are considered the "primary" part of the type
251                     // and are visited by shallow visitors.
252                     self.visit_predicates(ty::GenericPredicates {
253                         parent: None,
254                         predicates: tcx.explicit_item_bounds(def_id),
255                     })?;
256                 }
257             }
258             // These types don't have their own def-ids (but may have subcomponents
259             // with def-ids that should be visited recursively).
260             ty::Bool
261             | ty::Char
262             | ty::Int(..)
263             | ty::Uint(..)
264             | ty::Float(..)
265             | ty::Str
266             | ty::Never
267             | ty::Array(..)
268             | ty::Slice(..)
269             | ty::Tuple(..)
270             | ty::RawPtr(..)
271             | ty::Ref(..)
272             | ty::FnPtr(..)
273             | ty::Param(..)
274             | ty::Error(_)
275             | ty::GeneratorWitness(..) => {}
276             ty::Bound(..) | ty::Placeholder(..) | ty::Infer(..) => {
277                 bug!("unexpected type: {:?}", ty)
278             }
279         }
280
281         if self.def_id_visitor.shallow() {
282             ControlFlow::CONTINUE
283         } else {
284             ty.super_visit_with(self)
285         }
286     }
287
288     fn visit_const(&mut self, c: Const<'tcx>) -> ControlFlow<Self::BreakTy> {
289         self.visit_ty(c.ty())?;
290         let tcx = self.def_id_visitor.tcx();
291         if let Ok(Some(ct)) = AbstractConst::from_const(tcx, c) {
292             self.visit_abstract_const_expr(tcx, ct)?;
293         }
294         ControlFlow::CONTINUE
295     }
296 }
297
298 fn min(vis1: ty::Visibility, vis2: ty::Visibility, tcx: TyCtxt<'_>) -> ty::Visibility {
299     if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
300 }
301
302 ////////////////////////////////////////////////////////////////////////////////
303 /// Visitor used to determine impl visibility and reachability.
304 ////////////////////////////////////////////////////////////////////////////////
305
306 struct FindMin<'a, 'tcx, VL: VisibilityLike> {
307     tcx: TyCtxt<'tcx>,
308     access_levels: &'a AccessLevels,
309     min: VL,
310 }
311
312 impl<'a, 'tcx, VL: VisibilityLike> DefIdVisitor<'tcx> for FindMin<'a, 'tcx, VL> {
313     fn tcx(&self) -> TyCtxt<'tcx> {
314         self.tcx
315     }
316     fn shallow(&self) -> bool {
317         VL::SHALLOW
318     }
319     fn skip_assoc_tys(&self) -> bool {
320         true
321     }
322     fn visit_def_id(
323         &mut self,
324         def_id: DefId,
325         _kind: &str,
326         _descr: &dyn fmt::Display,
327     ) -> ControlFlow<Self::BreakTy> {
328         self.min = VL::new_min(self, def_id);
329         ControlFlow::CONTINUE
330     }
331 }
332
333 trait VisibilityLike: Sized {
334     const MAX: Self;
335     const SHALLOW: bool = false;
336     fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self;
337
338     // Returns an over-approximation (`skip_assoc_tys` = true) of visibility due to
339     // associated types for which we can't determine visibility precisely.
340     fn of_impl(def_id: LocalDefId, tcx: TyCtxt<'_>, access_levels: &AccessLevels) -> Self {
341         let mut find = FindMin { tcx, access_levels, min: Self::MAX };
342         find.visit(tcx.type_of(def_id));
343         if let Some(trait_ref) = tcx.impl_trait_ref(def_id) {
344             find.visit_trait(trait_ref);
345         }
346         find.min
347     }
348 }
349 impl VisibilityLike for ty::Visibility {
350     const MAX: Self = ty::Visibility::Public;
351     fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self {
352         min(find.tcx.visibility(def_id), find.min, find.tcx)
353     }
354 }
355 impl VisibilityLike for Option<AccessLevel> {
356     const MAX: Self = Some(AccessLevel::Public);
357     // Type inference is very smart sometimes.
358     // It can make an impl reachable even some components of its type or trait are unreachable.
359     // E.g. methods of `impl ReachableTrait<UnreachableTy> for ReachableTy<UnreachableTy> { ... }`
360     // can be usable from other crates (#57264). So we skip substs when calculating reachability
361     // and consider an impl reachable if its "shallow" type and trait are reachable.
362     //
363     // The assumption we make here is that type-inference won't let you use an impl without knowing
364     // both "shallow" version of its self type and "shallow" version of its trait if it exists
365     // (which require reaching the `DefId`s in them).
366     const SHALLOW: bool = true;
367     fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self {
368         cmp::min(
369             if let Some(def_id) = def_id.as_local() {
370                 find.access_levels.map.get(&def_id).copied()
371             } else {
372                 Self::MAX
373             },
374             find.min,
375         )
376     }
377 }
378
379 ////////////////////////////////////////////////////////////////////////////////
380 /// The embargo visitor, used to determine the exports of the AST.
381 ////////////////////////////////////////////////////////////////////////////////
382
383 struct EmbargoVisitor<'tcx> {
384     tcx: TyCtxt<'tcx>,
385
386     /// Accessibility levels for reachable nodes.
387     access_levels: AccessLevels,
388     /// A set of pairs corresponding to modules, where the first module is
389     /// reachable via a macro that's defined in the second module. This cannot
390     /// be represented as reachable because it can't handle the following case:
391     ///
392     /// pub mod n {                         // Should be `Public`
393     ///     pub(crate) mod p {              // Should *not* be accessible
394     ///         pub fn f() -> i32 { 12 }    // Must be `Reachable`
395     ///     }
396     /// }
397     /// pub macro m() {
398     ///     n::p::f()
399     /// }
400     macro_reachable: FxHashSet<(LocalDefId, LocalDefId)>,
401     /// Previous accessibility level; `None` means unreachable.
402     prev_level: Option<AccessLevel>,
403     /// Has something changed in the level map?
404     changed: bool,
405 }
406
407 struct ReachEverythingInTheInterfaceVisitor<'a, 'tcx> {
408     access_level: Option<AccessLevel>,
409     item_def_id: LocalDefId,
410     ev: &'a mut EmbargoVisitor<'tcx>,
411 }
412
413 impl<'tcx> EmbargoVisitor<'tcx> {
414     fn get(&self, def_id: LocalDefId) -> Option<AccessLevel> {
415         self.access_levels.map.get(&def_id).copied()
416     }
417
418     fn update_with_hir_id(
419         &mut self,
420         hir_id: hir::HirId,
421         level: Option<AccessLevel>,
422     ) -> Option<AccessLevel> {
423         let def_id = self.tcx.hir().local_def_id(hir_id);
424         self.update(def_id, level)
425     }
426
427     /// Updates node level and returns the updated level.
428     fn update(&mut self, def_id: LocalDefId, level: Option<AccessLevel>) -> Option<AccessLevel> {
429         let old_level = self.get(def_id);
430         // Accessibility levels can only grow.
431         if level > old_level {
432             self.access_levels.map.insert(def_id, level.unwrap());
433             self.changed = true;
434             level
435         } else {
436             old_level
437         }
438     }
439
440     fn reach(
441         &mut self,
442         def_id: LocalDefId,
443         access_level: Option<AccessLevel>,
444     ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
445         ReachEverythingInTheInterfaceVisitor {
446             access_level: cmp::min(access_level, Some(AccessLevel::Reachable)),
447             item_def_id: def_id,
448             ev: self,
449         }
450     }
451
452     // We have to make sure that the items that macros might reference
453     // are reachable, since they might be exported transitively.
454     fn update_reachability_from_macro(&mut self, local_def_id: LocalDefId, md: &MacroDef) {
455         // Non-opaque macros cannot make other items more accessible than they already are.
456
457         let hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id);
458         let attrs = self.tcx.hir().attrs(hir_id);
459         if attr::find_transparency(attrs, md.macro_rules).0 != Transparency::Opaque {
460             return;
461         }
462
463         let macro_module_def_id = self.tcx.local_parent(local_def_id);
464         if self.tcx.hir().opt_def_kind(macro_module_def_id) != Some(DefKind::Mod) {
465             // The macro's parent doesn't correspond to a `mod`, return early (#63164, #65252).
466             return;
467         }
468
469         if self.get(local_def_id).is_none() {
470             return;
471         }
472
473         // Since we are starting from an externally visible module,
474         // all the parents in the loop below are also guaranteed to be modules.
475         let mut module_def_id = macro_module_def_id;
476         loop {
477             let changed_reachability =
478                 self.update_macro_reachable(module_def_id, macro_module_def_id);
479             if changed_reachability || module_def_id == CRATE_DEF_ID {
480                 break;
481             }
482             module_def_id = self.tcx.local_parent(module_def_id);
483         }
484     }
485
486     /// Updates the item as being reachable through a macro defined in the given
487     /// module. Returns `true` if the level has changed.
488     fn update_macro_reachable(
489         &mut self,
490         module_def_id: LocalDefId,
491         defining_mod: LocalDefId,
492     ) -> bool {
493         if self.macro_reachable.insert((module_def_id, defining_mod)) {
494             self.update_macro_reachable_mod(module_def_id, defining_mod);
495             true
496         } else {
497             false
498         }
499     }
500
501     fn update_macro_reachable_mod(&mut self, module_def_id: LocalDefId, defining_mod: LocalDefId) {
502         let module = self.tcx.hir().get_module(module_def_id).0;
503         for item_id in module.item_ids {
504             let def_kind = self.tcx.def_kind(item_id.def_id);
505             let vis = self.tcx.visibility(item_id.def_id);
506             self.update_macro_reachable_def(item_id.def_id, def_kind, vis, defining_mod);
507         }
508         if let Some(exports) = self.tcx.module_reexports(module_def_id) {
509             for export in exports {
510                 if export.vis.is_accessible_from(defining_mod.to_def_id(), self.tcx) {
511                     if let Res::Def(def_kind, def_id) = export.res {
512                         if let Some(def_id) = def_id.as_local() {
513                             let vis = self.tcx.visibility(def_id.to_def_id());
514                             self.update_macro_reachable_def(def_id, def_kind, vis, defining_mod);
515                         }
516                     }
517                 }
518             }
519         }
520     }
521
522     fn update_macro_reachable_def(
523         &mut self,
524         def_id: LocalDefId,
525         def_kind: DefKind,
526         vis: ty::Visibility,
527         module: LocalDefId,
528     ) {
529         let level = Some(AccessLevel::Reachable);
530         if vis.is_public() {
531             self.update(def_id, level);
532         }
533         match def_kind {
534             // No type privacy, so can be directly marked as reachable.
535             DefKind::Const | DefKind::Static(_) | DefKind::TraitAlias | DefKind::TyAlias => {
536                 if vis.is_accessible_from(module.to_def_id(), self.tcx) {
537                     self.update(def_id, level);
538                 }
539             }
540
541             // Hygiene isn't really implemented for `macro_rules!` macros at the
542             // moment. Accordingly, marking them as reachable is unwise. `macro` macros
543             // have normal hygiene, so we can treat them like other items without type
544             // privacy and mark them reachable.
545             DefKind::Macro(_) => {
546                 let item = self.tcx.hir().expect_item(def_id);
547                 if let hir::ItemKind::Macro(MacroDef { macro_rules: false, .. }, _) = item.kind {
548                     if vis.is_accessible_from(module.to_def_id(), self.tcx) {
549                         self.update(def_id, level);
550                     }
551                 }
552             }
553
554             // We can't use a module name as the final segment of a path, except
555             // in use statements. Since re-export checking doesn't consider
556             // hygiene these don't need to be marked reachable. The contents of
557             // the module, however may be reachable.
558             DefKind::Mod => {
559                 if vis.is_accessible_from(module.to_def_id(), self.tcx) {
560                     self.update_macro_reachable(def_id, module);
561                 }
562             }
563
564             DefKind::Struct | DefKind::Union => {
565                 // While structs and unions have type privacy, their fields do not.
566                 if vis.is_public() {
567                     let item = self.tcx.hir().expect_item(def_id);
568                     if let hir::ItemKind::Struct(ref struct_def, _)
569                     | hir::ItemKind::Union(ref struct_def, _) = item.kind
570                     {
571                         for field in struct_def.fields() {
572                             let def_id = self.tcx.hir().local_def_id(field.hir_id);
573                             let field_vis = self.tcx.visibility(def_id);
574                             if field_vis.is_accessible_from(module.to_def_id(), self.tcx) {
575                                 self.reach(def_id, level).ty();
576                             }
577                         }
578                     } else {
579                         bug!("item {:?} with DefKind {:?}", item, def_kind);
580                     }
581                 }
582             }
583
584             // These have type privacy, so are not reachable unless they're
585             // public, or are not namespaced at all.
586             DefKind::AssocConst
587             | DefKind::AssocTy
588             | DefKind::ConstParam
589             | DefKind::Ctor(_, _)
590             | DefKind::Enum
591             | DefKind::ForeignTy
592             | DefKind::Fn
593             | DefKind::OpaqueTy
594             | DefKind::AssocFn
595             | DefKind::Trait
596             | DefKind::TyParam
597             | DefKind::Variant
598             | DefKind::LifetimeParam
599             | DefKind::ExternCrate
600             | DefKind::Use
601             | DefKind::ForeignMod
602             | DefKind::AnonConst
603             | DefKind::InlineConst
604             | DefKind::Field
605             | DefKind::GlobalAsm
606             | DefKind::Impl
607             | DefKind::Closure
608             | DefKind::Generator => (),
609         }
610     }
611 }
612
613 impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> {
614     type NestedFilter = nested_filter::All;
615
616     /// We want to visit items in the context of their containing
617     /// module and so forth, so supply a crate for doing a deep walk.
618     fn nested_visit_map(&mut self) -> Self::Map {
619         self.tcx.hir()
620     }
621
622     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
623         let item_level = match item.kind {
624             hir::ItemKind::Impl { .. } => {
625                 let impl_level =
626                     Option::<AccessLevel>::of_impl(item.def_id, self.tcx, &self.access_levels);
627                 self.update(item.def_id, impl_level)
628             }
629             _ => self.get(item.def_id),
630         };
631
632         // Update levels of nested things.
633         match item.kind {
634             hir::ItemKind::Enum(ref def, _) => {
635                 for variant in def.variants {
636                     let variant_level = self.update_with_hir_id(variant.id, item_level);
637                     if let Some(ctor_hir_id) = variant.data.ctor_hir_id() {
638                         self.update_with_hir_id(ctor_hir_id, item_level);
639                     }
640                     for field in variant.data.fields() {
641                         self.update_with_hir_id(field.hir_id, variant_level);
642                     }
643                 }
644             }
645             hir::ItemKind::Impl(ref impl_) => {
646                 for impl_item_ref in impl_.items {
647                     if impl_.of_trait.is_some()
648                         || self.tcx.visibility(impl_item_ref.id.def_id) == ty::Visibility::Public
649                     {
650                         self.update(impl_item_ref.id.def_id, item_level);
651                     }
652                 }
653             }
654             hir::ItemKind::Trait(.., trait_item_refs) => {
655                 for trait_item_ref in trait_item_refs {
656                     self.update(trait_item_ref.id.def_id, item_level);
657                 }
658             }
659             hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => {
660                 if let Some(ctor_hir_id) = def.ctor_hir_id() {
661                     self.update_with_hir_id(ctor_hir_id, item_level);
662                 }
663                 for field in def.fields() {
664                     let def_id = self.tcx.hir().local_def_id(field.hir_id);
665                     let vis = self.tcx.visibility(def_id);
666                     if vis.is_public() {
667                         self.update_with_hir_id(field.hir_id, item_level);
668                     }
669                 }
670             }
671             hir::ItemKind::Macro(ref macro_def, _) => {
672                 self.update_reachability_from_macro(item.def_id, macro_def);
673             }
674             hir::ItemKind::ForeignMod { items, .. } => {
675                 for foreign_item in items {
676                     if self.tcx.visibility(foreign_item.id.def_id) == ty::Visibility::Public {
677                         self.update(foreign_item.id.def_id, item_level);
678                     }
679                 }
680             }
681
682             hir::ItemKind::OpaqueTy(..)
683             | hir::ItemKind::Use(..)
684             | hir::ItemKind::Static(..)
685             | hir::ItemKind::Const(..)
686             | hir::ItemKind::GlobalAsm(..)
687             | hir::ItemKind::TyAlias(..)
688             | hir::ItemKind::Mod(..)
689             | hir::ItemKind::TraitAlias(..)
690             | hir::ItemKind::Fn(..)
691             | hir::ItemKind::ExternCrate(..) => {}
692         }
693
694         // Mark all items in interfaces of reachable items as reachable.
695         match item.kind {
696             // The interface is empty.
697             hir::ItemKind::Macro(..) | hir::ItemKind::ExternCrate(..) => {}
698             // All nested items are checked by `visit_item`.
699             hir::ItemKind::Mod(..) => {}
700             // Handled in the access level of in rustc_resolve
701             hir::ItemKind::Use(..) => {}
702             // The interface is empty.
703             hir::ItemKind::GlobalAsm(..) => {}
704             hir::ItemKind::OpaqueTy(..) => {
705                 // HACK(jynelson): trying to infer the type of `impl trait` breaks `async-std` (and `pub async fn` in general)
706                 // Since rustdoc never needs to do codegen and doesn't care about link-time reachability,
707                 // mark this as unreachable.
708                 // See https://github.com/rust-lang/rust/issues/75100
709                 if !self.tcx.sess.opts.actually_rustdoc {
710                     // FIXME: This is some serious pessimization intended to workaround deficiencies
711                     // in the reachability pass (`middle/reachable.rs`). Types are marked as link-time
712                     // reachable if they are returned via `impl Trait`, even from private functions.
713                     let exist_level =
714                         cmp::max(item_level, Some(AccessLevel::ReachableFromImplTrait));
715                     self.reach(item.def_id, exist_level).generics().predicates().ty();
716                 }
717             }
718             // Visit everything.
719             hir::ItemKind::Const(..)
720             | hir::ItemKind::Static(..)
721             | hir::ItemKind::Fn(..)
722             | hir::ItemKind::TyAlias(..) => {
723                 if item_level.is_some() {
724                     self.reach(item.def_id, item_level).generics().predicates().ty();
725                 }
726             }
727             hir::ItemKind::Trait(.., trait_item_refs) => {
728                 if item_level.is_some() {
729                     self.reach(item.def_id, item_level).generics().predicates();
730
731                     for trait_item_ref in trait_item_refs {
732                         let mut reach = self.reach(trait_item_ref.id.def_id, item_level);
733                         reach.generics().predicates();
734
735                         if trait_item_ref.kind == AssocItemKind::Type
736                             && !trait_item_ref.defaultness.has_value()
737                         {
738                             // No type to visit.
739                         } else {
740                             reach.ty();
741                         }
742                     }
743                 }
744             }
745             hir::ItemKind::TraitAlias(..) => {
746                 if item_level.is_some() {
747                     self.reach(item.def_id, item_level).generics().predicates();
748                 }
749             }
750             // Visit everything except for private impl items.
751             hir::ItemKind::Impl(ref impl_) => {
752                 if item_level.is_some() {
753                     self.reach(item.def_id, item_level).generics().predicates().ty().trait_ref();
754
755                     for impl_item_ref in impl_.items {
756                         let impl_item_level = self.get(impl_item_ref.id.def_id);
757                         if impl_item_level.is_some() {
758                             self.reach(impl_item_ref.id.def_id, impl_item_level)
759                                 .generics()
760                                 .predicates()
761                                 .ty();
762                         }
763                     }
764                 }
765             }
766
767             // Visit everything, but enum variants have their own levels.
768             hir::ItemKind::Enum(ref def, _) => {
769                 if item_level.is_some() {
770                     self.reach(item.def_id, item_level).generics().predicates();
771                 }
772                 for variant in def.variants {
773                     let variant_level = self.get(self.tcx.hir().local_def_id(variant.id));
774                     if variant_level.is_some() {
775                         for field in variant.data.fields() {
776                             self.reach(self.tcx.hir().local_def_id(field.hir_id), variant_level)
777                                 .ty();
778                         }
779                         // Corner case: if the variant is reachable, but its
780                         // enum is not, make the enum reachable as well.
781                         self.reach(item.def_id, variant_level).ty();
782                     }
783                     if let Some(hir_id) = variant.data.ctor_hir_id() {
784                         let ctor_def_id = self.tcx.hir().local_def_id(hir_id);
785                         let ctor_level = self.get(ctor_def_id);
786                         if ctor_level.is_some() {
787                             self.reach(item.def_id, ctor_level).ty();
788                         }
789                     }
790                 }
791             }
792             // Visit everything, but foreign items have their own levels.
793             hir::ItemKind::ForeignMod { items, .. } => {
794                 for foreign_item in items {
795                     let foreign_item_level = self.get(foreign_item.id.def_id);
796                     if foreign_item_level.is_some() {
797                         self.reach(foreign_item.id.def_id, foreign_item_level)
798                             .generics()
799                             .predicates()
800                             .ty();
801                     }
802                 }
803             }
804             // Visit everything except for private fields.
805             hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
806                 if item_level.is_some() {
807                     self.reach(item.def_id, item_level).generics().predicates();
808                     for field in struct_def.fields() {
809                         let def_id = self.tcx.hir().local_def_id(field.hir_id);
810                         let field_level = self.get(def_id);
811                         if field_level.is_some() {
812                             self.reach(def_id, field_level).ty();
813                         }
814                     }
815                 }
816                 if let Some(hir_id) = struct_def.ctor_hir_id() {
817                     let ctor_def_id = self.tcx.hir().local_def_id(hir_id);
818                     let ctor_level = self.get(ctor_def_id);
819                     if ctor_level.is_some() {
820                         self.reach(item.def_id, ctor_level).ty();
821                     }
822                 }
823             }
824         }
825
826         let orig_level = mem::replace(&mut self.prev_level, item_level);
827         intravisit::walk_item(self, item);
828         self.prev_level = orig_level;
829     }
830
831     fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
832         // Blocks can have public items, for example impls, but they always
833         // start as completely private regardless of publicity of a function,
834         // constant, type, field, etc., in which this block resides.
835         let orig_level = mem::replace(&mut self.prev_level, None);
836         intravisit::walk_block(self, b);
837         self.prev_level = orig_level;
838     }
839 }
840
841 impl ReachEverythingInTheInterfaceVisitor<'_, '_> {
842     fn generics(&mut self) -> &mut Self {
843         for param in &self.ev.tcx.generics_of(self.item_def_id).params {
844             match param.kind {
845                 GenericParamDefKind::Lifetime => {}
846                 GenericParamDefKind::Type { has_default, .. } => {
847                     if has_default {
848                         self.visit(self.ev.tcx.type_of(param.def_id));
849                     }
850                 }
851                 GenericParamDefKind::Const { has_default } => {
852                     self.visit(self.ev.tcx.type_of(param.def_id));
853                     if has_default {
854                         self.visit(self.ev.tcx.const_param_default(param.def_id));
855                     }
856                 }
857             }
858         }
859         self
860     }
861
862     fn predicates(&mut self) -> &mut Self {
863         self.visit_predicates(self.ev.tcx.predicates_of(self.item_def_id));
864         self
865     }
866
867     fn ty(&mut self) -> &mut Self {
868         self.visit(self.ev.tcx.type_of(self.item_def_id));
869         self
870     }
871
872     fn trait_ref(&mut self) -> &mut Self {
873         if let Some(trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) {
874             self.visit_trait(trait_ref);
875         }
876         self
877     }
878 }
879
880 impl<'tcx> DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
881     fn tcx(&self) -> TyCtxt<'tcx> {
882         self.ev.tcx
883     }
884     fn visit_def_id(
885         &mut self,
886         def_id: DefId,
887         _kind: &str,
888         _descr: &dyn fmt::Display,
889     ) -> ControlFlow<Self::BreakTy> {
890         if let Some(def_id) = def_id.as_local() {
891             if let (ty::Visibility::Public, _) | (_, Some(AccessLevel::ReachableFromImplTrait)) =
892                 (self.tcx().visibility(def_id.to_def_id()), self.access_level)
893             {
894                 self.ev.update(def_id, self.access_level);
895             }
896         }
897         ControlFlow::CONTINUE
898     }
899 }
900
901 //////////////////////////////////////////////////////////////////////////////////////
902 /// Name privacy visitor, checks privacy and reports violations.
903 /// Most of name privacy checks are performed during the main resolution phase,
904 /// or later in type checking when field accesses and associated items are resolved.
905 /// This pass performs remaining checks for fields in struct expressions and patterns.
906 //////////////////////////////////////////////////////////////////////////////////////
907
908 struct NamePrivacyVisitor<'tcx> {
909     tcx: TyCtxt<'tcx>,
910     maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
911     current_item: LocalDefId,
912 }
913
914 impl<'tcx> NamePrivacyVisitor<'tcx> {
915     /// Gets the type-checking results for the current body.
916     /// As this will ICE if called outside bodies, only call when working with
917     /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
918     #[track_caller]
919     fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
920         self.maybe_typeck_results
921             .expect("`NamePrivacyVisitor::typeck_results` called outside of body")
922     }
923
924     // Checks that a field in a struct constructor (expression or pattern) is accessible.
925     fn check_field(
926         &mut self,
927         use_ctxt: Span,        // syntax context of the field name at the use site
928         span: Span,            // span of the field pattern, e.g., `x: 0`
929         def: ty::AdtDef<'tcx>, // definition of the struct or enum
930         field: &'tcx ty::FieldDef,
931         in_update_syntax: bool,
932     ) {
933         if def.is_enum() {
934             return;
935         }
936
937         // definition of the field
938         let ident = Ident::new(kw::Empty, use_ctxt);
939         let hir_id = self.tcx.hir().local_def_id_to_hir_id(self.current_item);
940         let def_id = self.tcx.adjust_ident_and_get_scope(ident, def.did(), hir_id).1;
941         if !field.vis.is_accessible_from(def_id, self.tcx) {
942             self.tcx.sess.emit_err(FieldIsPrivate {
943                 span,
944                 field_name: field.name,
945                 variant_descr: def.variant_descr(),
946                 def_path_str: self.tcx.def_path_str(def.did()),
947                 label: if in_update_syntax {
948                     FieldIsPrivateLabel::IsUpdateSyntax { span, field_name: field.name }
949                 } else {
950                     FieldIsPrivateLabel::Other { span }
951                 },
952             });
953         }
954     }
955 }
956
957 impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> {
958     type NestedFilter = nested_filter::All;
959
960     /// We want to visit items in the context of their containing
961     /// module and so forth, so supply a crate for doing a deep walk.
962     fn nested_visit_map(&mut self) -> Self::Map {
963         self.tcx.hir()
964     }
965
966     fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) {
967         // Don't visit nested modules, since we run a separate visitor walk
968         // for each module in `privacy_access_levels`
969     }
970
971     fn visit_nested_body(&mut self, body: hir::BodyId) {
972         let old_maybe_typeck_results =
973             self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
974         let body = self.tcx.hir().body(body);
975         self.visit_body(body);
976         self.maybe_typeck_results = old_maybe_typeck_results;
977     }
978
979     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
980         let orig_current_item = mem::replace(&mut self.current_item, item.def_id);
981         intravisit::walk_item(self, item);
982         self.current_item = orig_current_item;
983     }
984
985     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
986         if let hir::ExprKind::Struct(qpath, fields, ref base) = expr.kind {
987             let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
988             let adt = self.typeck_results().expr_ty(expr).ty_adt_def().unwrap();
989             let variant = adt.variant_of_res(res);
990             if let Some(base) = *base {
991                 // If the expression uses FRU we need to make sure all the unmentioned fields
992                 // are checked for privacy (RFC 736). Rather than computing the set of
993                 // unmentioned fields, just check them all.
994                 for (vf_index, variant_field) in variant.fields.iter().enumerate() {
995                     let field = fields.iter().find(|f| {
996                         self.tcx.field_index(f.hir_id, self.typeck_results()) == vf_index
997                     });
998                     let (use_ctxt, span) = match field {
999                         Some(field) => (field.ident.span, field.span),
1000                         None => (base.span, base.span),
1001                     };
1002                     self.check_field(use_ctxt, span, adt, variant_field, true);
1003                 }
1004             } else {
1005                 for field in fields {
1006                     let use_ctxt = field.ident.span;
1007                     let index = self.tcx.field_index(field.hir_id, self.typeck_results());
1008                     self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false);
1009                 }
1010             }
1011         }
1012
1013         intravisit::walk_expr(self, expr);
1014     }
1015
1016     fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
1017         if let PatKind::Struct(ref qpath, fields, _) = pat.kind {
1018             let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
1019             let adt = self.typeck_results().pat_ty(pat).ty_adt_def().unwrap();
1020             let variant = adt.variant_of_res(res);
1021             for field in fields {
1022                 let use_ctxt = field.ident.span;
1023                 let index = self.tcx.field_index(field.hir_id, self.typeck_results());
1024                 self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false);
1025             }
1026         }
1027
1028         intravisit::walk_pat(self, pat);
1029     }
1030 }
1031
1032 ////////////////////////////////////////////////////////////////////////////////////////////
1033 /// Type privacy visitor, checks types for privacy and reports violations.
1034 /// Both explicitly written types and inferred types of expressions and patterns are checked.
1035 /// Checks are performed on "semantic" types regardless of names and their hygiene.
1036 ////////////////////////////////////////////////////////////////////////////////////////////
1037
1038 struct TypePrivacyVisitor<'tcx> {
1039     tcx: TyCtxt<'tcx>,
1040     maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
1041     current_item: LocalDefId,
1042     span: Span,
1043 }
1044
1045 impl<'tcx> TypePrivacyVisitor<'tcx> {
1046     /// Gets the type-checking results for the current body.
1047     /// As this will ICE if called outside bodies, only call when working with
1048     /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
1049     #[track_caller]
1050     fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
1051         self.maybe_typeck_results
1052             .expect("`TypePrivacyVisitor::typeck_results` called outside of body")
1053     }
1054
1055     fn item_is_accessible(&self, did: DefId) -> bool {
1056         self.tcx.visibility(did).is_accessible_from(self.current_item.to_def_id(), self.tcx)
1057     }
1058
1059     // Take node-id of an expression or pattern and check its type for privacy.
1060     fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
1061         self.span = span;
1062         let typeck_results = self.typeck_results();
1063         let result: ControlFlow<()> = try {
1064             self.visit(typeck_results.node_type(id))?;
1065             self.visit(typeck_results.node_substs(id))?;
1066             if let Some(adjustments) = typeck_results.adjustments().get(id) {
1067                 adjustments.iter().try_for_each(|adjustment| self.visit(adjustment.target))?;
1068             }
1069         };
1070         result.is_break()
1071     }
1072
1073     fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1074         let is_error = !self.item_is_accessible(def_id);
1075         if is_error {
1076             self.tcx.sess.emit_err(ItemIsPrivate {
1077                 span: self.span,
1078                 kind,
1079                 descr: descr.to_string(),
1080             });
1081         }
1082         is_error
1083     }
1084 }
1085
1086 impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> {
1087     type NestedFilter = nested_filter::All;
1088
1089     /// We want to visit items in the context of their containing
1090     /// module and so forth, so supply a crate for doing a deep walk.
1091     fn nested_visit_map(&mut self) -> Self::Map {
1092         self.tcx.hir()
1093     }
1094
1095     fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) {
1096         // Don't visit nested modules, since we run a separate visitor walk
1097         // for each module in `privacy_access_levels`
1098     }
1099
1100     fn visit_nested_body(&mut self, body: hir::BodyId) {
1101         let old_maybe_typeck_results =
1102             self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
1103         let body = self.tcx.hir().body(body);
1104         self.visit_body(body);
1105         self.maybe_typeck_results = old_maybe_typeck_results;
1106     }
1107
1108     fn visit_generic_arg(&mut self, generic_arg: &'tcx hir::GenericArg<'tcx>) {
1109         match generic_arg {
1110             hir::GenericArg::Type(t) => self.visit_ty(t),
1111             hir::GenericArg::Infer(inf) => self.visit_infer(inf),
1112             hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {}
1113         }
1114     }
1115
1116     fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) {
1117         self.span = hir_ty.span;
1118         if let Some(typeck_results) = self.maybe_typeck_results {
1119             // Types in bodies.
1120             if self.visit(typeck_results.node_type(hir_ty.hir_id)).is_break() {
1121                 return;
1122             }
1123         } else {
1124             // Types in signatures.
1125             // FIXME: This is very ineffective. Ideally each HIR type should be converted
1126             // into a semantic type only once and the result should be cached somehow.
1127             if self.visit(rustc_typeck::hir_ty_to_ty(self.tcx, hir_ty)).is_break() {
1128                 return;
1129             }
1130         }
1131
1132         intravisit::walk_ty(self, hir_ty);
1133     }
1134
1135     fn visit_infer(&mut self, inf: &'tcx hir::InferArg) {
1136         self.span = inf.span;
1137         if let Some(typeck_results) = self.maybe_typeck_results {
1138             if let Some(ty) = typeck_results.node_type_opt(inf.hir_id) {
1139                 if self.visit(ty).is_break() {
1140                     return;
1141                 }
1142             } else {
1143                 // We don't do anything for const infers here.
1144             }
1145         } else {
1146             bug!("visit_infer without typeck_results");
1147         }
1148         intravisit::walk_inf(self, inf);
1149     }
1150
1151     fn visit_trait_ref(&mut self, trait_ref: &'tcx hir::TraitRef<'tcx>) {
1152         self.span = trait_ref.path.span;
1153         if self.maybe_typeck_results.is_none() {
1154             // Avoid calling `hir_trait_to_predicates` in bodies, it will ICE.
1155             // The traits' privacy in bodies is already checked as a part of trait object types.
1156             let bounds = rustc_typeck::hir_trait_to_predicates(
1157                 self.tcx,
1158                 trait_ref,
1159                 // NOTE: This isn't really right, but the actual type doesn't matter here. It's
1160                 // just required by `ty::TraitRef`.
1161                 self.tcx.types.never,
1162             );
1163
1164             for (trait_predicate, _, _) in bounds.trait_bounds {
1165                 if self.visit_trait(trait_predicate.skip_binder()).is_break() {
1166                     return;
1167                 }
1168             }
1169
1170             for (poly_predicate, _) in bounds.projection_bounds {
1171                 let pred = poly_predicate.skip_binder();
1172                 let poly_pred_term = self.visit(pred.term);
1173                 if poly_pred_term.is_break()
1174                     || self.visit_projection_ty(pred.projection_ty).is_break()
1175                 {
1176                     return;
1177                 }
1178             }
1179         }
1180
1181         intravisit::walk_trait_ref(self, trait_ref);
1182     }
1183
1184     // Check types of expressions
1185     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1186         if self.check_expr_pat_type(expr.hir_id, expr.span) {
1187             // Do not check nested expressions if the error already happened.
1188             return;
1189         }
1190         match expr.kind {
1191             hir::ExprKind::Assign(_, rhs, _) | hir::ExprKind::Match(rhs, ..) => {
1192                 // Do not report duplicate errors for `x = y` and `match x { ... }`.
1193                 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
1194                     return;
1195                 }
1196             }
1197             hir::ExprKind::MethodCall(segment, ..) => {
1198                 // Method calls have to be checked specially.
1199                 self.span = segment.ident.span;
1200                 if let Some(def_id) = self.typeck_results().type_dependent_def_id(expr.hir_id) {
1201                     if self.visit(self.tcx.type_of(def_id)).is_break() {
1202                         return;
1203                     }
1204                 } else {
1205                     self.tcx
1206                         .sess
1207                         .delay_span_bug(expr.span, "no type-dependent def for method call");
1208                 }
1209             }
1210             _ => {}
1211         }
1212
1213         intravisit::walk_expr(self, expr);
1214     }
1215
1216     // Prohibit access to associated items with insufficient nominal visibility.
1217     //
1218     // Additionally, until better reachability analysis for macros 2.0 is available,
1219     // we prohibit access to private statics from other crates, this allows to give
1220     // more code internal visibility at link time. (Access to private functions
1221     // is already prohibited by type privacy for function types.)
1222     fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) {
1223         let def = match qpath {
1224             hir::QPath::Resolved(_, path) => match path.res {
1225                 Res::Def(kind, def_id) => Some((kind, def_id)),
1226                 _ => None,
1227             },
1228             hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
1229                 .maybe_typeck_results
1230                 .and_then(|typeck_results| typeck_results.type_dependent_def(id)),
1231         };
1232         let def = def.filter(|(kind, _)| {
1233             matches!(
1234                 kind,
1235                 DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static(_)
1236             )
1237         });
1238         if let Some((kind, def_id)) = def {
1239             let is_local_static =
1240                 if let DefKind::Static(_) = kind { def_id.is_local() } else { false };
1241             if !self.item_is_accessible(def_id) && !is_local_static {
1242                 let sess = self.tcx.sess;
1243                 let sm = sess.source_map();
1244                 let name = match qpath {
1245                     hir::QPath::Resolved(..) | hir::QPath::LangItem(..) => {
1246                         sm.span_to_snippet(qpath.span()).ok()
1247                     }
1248                     hir::QPath::TypeRelative(_, segment) => Some(segment.ident.to_string()),
1249                 };
1250                 let kind = kind.descr(def_id);
1251                 let _ = match name {
1252                     Some(name) => sess.emit_err(ItemIsPrivate { span, kind, descr: name }),
1253                     None => sess.emit_err(UnnamedItemIsPrivate { span, kind }),
1254                 };
1255                 return;
1256             }
1257         }
1258
1259         intravisit::walk_qpath(self, qpath, id, span);
1260     }
1261
1262     // Check types of patterns.
1263     fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) {
1264         if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
1265             // Do not check nested patterns if the error already happened.
1266             return;
1267         }
1268
1269         intravisit::walk_pat(self, pattern);
1270     }
1271
1272     fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) {
1273         if let Some(init) = local.init {
1274             if self.check_expr_pat_type(init.hir_id, init.span) {
1275                 // Do not report duplicate errors for `let x = y`.
1276                 return;
1277             }
1278         }
1279
1280         intravisit::walk_local(self, local);
1281     }
1282
1283     // Check types in item interfaces.
1284     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1285         let orig_current_item = mem::replace(&mut self.current_item, item.def_id);
1286         let old_maybe_typeck_results = self.maybe_typeck_results.take();
1287         intravisit::walk_item(self, item);
1288         self.maybe_typeck_results = old_maybe_typeck_results;
1289         self.current_item = orig_current_item;
1290     }
1291 }
1292
1293 impl<'tcx> DefIdVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1294     fn tcx(&self) -> TyCtxt<'tcx> {
1295         self.tcx
1296     }
1297     fn visit_def_id(
1298         &mut self,
1299         def_id: DefId,
1300         kind: &str,
1301         descr: &dyn fmt::Display,
1302     ) -> ControlFlow<Self::BreakTy> {
1303         if self.check_def_id(def_id, kind, descr) {
1304             ControlFlow::BREAK
1305         } else {
1306             ControlFlow::CONTINUE
1307         }
1308     }
1309 }
1310
1311 ///////////////////////////////////////////////////////////////////////////////
1312 /// Obsolete visitors for checking for private items in public interfaces.
1313 /// These visitors are supposed to be kept in frozen state and produce an
1314 /// "old error node set". For backward compatibility the new visitor reports
1315 /// warnings instead of hard errors when the erroneous node is not in this old set.
1316 ///////////////////////////////////////////////////////////////////////////////
1317
1318 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1319     tcx: TyCtxt<'tcx>,
1320     access_levels: &'a AccessLevels,
1321     in_variant: bool,
1322     // Set of errors produced by this obsolete visitor.
1323     old_error_set: HirIdSet,
1324 }
1325
1326 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1327     inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
1328     /// Whether the type refers to private types.
1329     contains_private: bool,
1330     /// Whether we've recurred at all (i.e., if we're pointing at the
1331     /// first type on which `visit_ty` was called).
1332     at_outer_type: bool,
1333     /// Whether that first type is a public path.
1334     outer_type_is_public_path: bool,
1335 }
1336
1337 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1338     fn path_is_private_type(&self, path: &hir::Path<'_>) -> bool {
1339         let did = match path.res {
1340             Res::PrimTy(..) | Res::SelfTy { .. } | Res::Err => return false,
1341             res => res.def_id(),
1342         };
1343
1344         // A path can only be private if:
1345         // it's in this crate...
1346         if let Some(did) = did.as_local() {
1347             // .. and it corresponds to a private type in the AST (this returns
1348             // `None` for type parameters).
1349             match self.tcx.hir().find(self.tcx.hir().local_def_id_to_hir_id(did)) {
1350                 Some(Node::Item(_)) => !self.tcx.visibility(did).is_public(),
1351                 Some(_) | None => false,
1352             }
1353         } else {
1354             false
1355         }
1356     }
1357
1358     fn trait_is_public(&self, trait_id: LocalDefId) -> bool {
1359         // FIXME: this would preferably be using `exported_items`, but all
1360         // traits are exported currently (see `EmbargoVisitor.exported_trait`).
1361         self.access_levels.is_public(trait_id)
1362     }
1363
1364     fn check_generic_bound(&mut self, bound: &hir::GenericBound<'_>) {
1365         if let hir::GenericBound::Trait(ref trait_ref, _) = *bound {
1366             if self.path_is_private_type(trait_ref.trait_ref.path) {
1367                 self.old_error_set.insert(trait_ref.trait_ref.hir_ref_id);
1368             }
1369         }
1370     }
1371
1372     fn item_is_public(&self, def_id: LocalDefId) -> bool {
1373         self.access_levels.is_reachable(def_id) || self.tcx.visibility(def_id).is_public()
1374     }
1375 }
1376
1377 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1378     fn visit_generic_arg(&mut self, generic_arg: &'v hir::GenericArg<'v>) {
1379         match generic_arg {
1380             hir::GenericArg::Type(t) => self.visit_ty(t),
1381             hir::GenericArg::Infer(inf) => self.visit_ty(&inf.to_ty()),
1382             hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {}
1383         }
1384     }
1385
1386     fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
1387         if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = ty.kind {
1388             if self.inner.path_is_private_type(path) {
1389                 self.contains_private = true;
1390                 // Found what we're looking for, so let's stop working.
1391                 return;
1392             }
1393         }
1394         if let hir::TyKind::Path(_) = ty.kind {
1395             if self.at_outer_type {
1396                 self.outer_type_is_public_path = true;
1397             }
1398         }
1399         self.at_outer_type = false;
1400         intravisit::walk_ty(self, ty)
1401     }
1402
1403     // Don't want to recurse into `[, .. expr]`.
1404     fn visit_expr(&mut self, _: &hir::Expr<'_>) {}
1405 }
1406
1407 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1408     type NestedFilter = nested_filter::All;
1409
1410     /// We want to visit items in the context of their containing
1411     /// module and so forth, so supply a crate for doing a deep walk.
1412     fn nested_visit_map(&mut self) -> Self::Map {
1413         self.tcx.hir()
1414     }
1415
1416     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1417         match item.kind {
1418             // Contents of a private mod can be re-exported, so we need
1419             // to check internals.
1420             hir::ItemKind::Mod(_) => {}
1421
1422             // An `extern {}` doesn't introduce a new privacy
1423             // namespace (the contents have their own privacies).
1424             hir::ItemKind::ForeignMod { .. } => {}
1425
1426             hir::ItemKind::Trait(.., bounds, _) => {
1427                 if !self.trait_is_public(item.def_id) {
1428                     return;
1429                 }
1430
1431                 for bound in bounds.iter() {
1432                     self.check_generic_bound(bound)
1433                 }
1434             }
1435
1436             // Impls need some special handling to try to offer useful
1437             // error messages without (too many) false positives
1438             // (i.e., we could just return here to not check them at
1439             // all, or some worse estimation of whether an impl is
1440             // publicly visible).
1441             hir::ItemKind::Impl(ref impl_) => {
1442                 // `impl [... for] Private` is never visible.
1443                 let self_contains_private;
1444                 // `impl [... for] Public<...>`, but not `impl [... for]
1445                 // Vec<Public>` or `(Public,)`, etc.
1446                 let self_is_public_path;
1447
1448                 // Check the properties of the `Self` type:
1449                 {
1450                     let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
1451                         inner: self,
1452                         contains_private: false,
1453                         at_outer_type: true,
1454                         outer_type_is_public_path: false,
1455                     };
1456                     visitor.visit_ty(impl_.self_ty);
1457                     self_contains_private = visitor.contains_private;
1458                     self_is_public_path = visitor.outer_type_is_public_path;
1459                 }
1460
1461                 // Miscellaneous info about the impl:
1462
1463                 // `true` iff this is `impl Private for ...`.
1464                 let not_private_trait = impl_.of_trait.as_ref().map_or(
1465                     true, // no trait counts as public trait
1466                     |tr| {
1467                         if let Some(def_id) = tr.path.res.def_id().as_local() {
1468                             self.trait_is_public(def_id)
1469                         } else {
1470                             true // external traits must be public
1471                         }
1472                     },
1473                 );
1474
1475                 // `true` iff this is a trait impl or at least one method is public.
1476                 //
1477                 // `impl Public { $( fn ...() {} )* }` is not visible.
1478                 //
1479                 // This is required over just using the methods' privacy
1480                 // directly because we might have `impl<T: Foo<Private>> ...`,
1481                 // and we shouldn't warn about the generics if all the methods
1482                 // are private (because `T` won't be visible externally).
1483                 let trait_or_some_public_method = impl_.of_trait.is_some()
1484                     || impl_.items.iter().any(|impl_item_ref| {
1485                         let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1486                         match impl_item.kind {
1487                             hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) => {
1488                                 self.access_levels.is_reachable(impl_item_ref.id.def_id)
1489                             }
1490                             hir::ImplItemKind::TyAlias(_) => false,
1491                         }
1492                     });
1493
1494                 if !self_contains_private && not_private_trait && trait_or_some_public_method {
1495                     intravisit::walk_generics(self, &impl_.generics);
1496
1497                     match impl_.of_trait {
1498                         None => {
1499                             for impl_item_ref in impl_.items {
1500                                 // This is where we choose whether to walk down
1501                                 // further into the impl to check its items. We
1502                                 // should only walk into public items so that we
1503                                 // don't erroneously report errors for private
1504                                 // types in private items.
1505                                 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1506                                 match impl_item.kind {
1507                                     hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..)
1508                                         if self.item_is_public(impl_item.def_id) =>
1509                                     {
1510                                         intravisit::walk_impl_item(self, impl_item)
1511                                     }
1512                                     hir::ImplItemKind::TyAlias(..) => {
1513                                         intravisit::walk_impl_item(self, impl_item)
1514                                     }
1515                                     _ => {}
1516                                 }
1517                             }
1518                         }
1519                         Some(ref tr) => {
1520                             // Any private types in a trait impl fall into three
1521                             // categories.
1522                             // 1. mentioned in the trait definition
1523                             // 2. mentioned in the type params/generics
1524                             // 3. mentioned in the associated types of the impl
1525                             //
1526                             // Those in 1. can only occur if the trait is in
1527                             // this crate and will have been warned about on the
1528                             // trait definition (there's no need to warn twice
1529                             // so we don't check the methods).
1530                             //
1531                             // Those in 2. are warned via walk_generics and this
1532                             // call here.
1533                             intravisit::walk_path(self, tr.path);
1534
1535                             // Those in 3. are warned with this call.
1536                             for impl_item_ref in impl_.items {
1537                                 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1538                                 if let hir::ImplItemKind::TyAlias(ty) = impl_item.kind {
1539                                     self.visit_ty(ty);
1540                                 }
1541                             }
1542                         }
1543                     }
1544                 } else if impl_.of_trait.is_none() && self_is_public_path {
1545                     // `impl Public<Private> { ... }`. Any public static
1546                     // methods will be visible as `Public::foo`.
1547                     let mut found_pub_static = false;
1548                     for impl_item_ref in impl_.items {
1549                         if self.access_levels.is_reachable(impl_item_ref.id.def_id)
1550                             || self.tcx.visibility(impl_item_ref.id.def_id)
1551                                 == ty::Visibility::Public
1552                         {
1553                             let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1554                             match impl_item_ref.kind {
1555                                 AssocItemKind::Const => {
1556                                     found_pub_static = true;
1557                                     intravisit::walk_impl_item(self, impl_item);
1558                                 }
1559                                 AssocItemKind::Fn { has_self: false } => {
1560                                     found_pub_static = true;
1561                                     intravisit::walk_impl_item(self, impl_item);
1562                                 }
1563                                 _ => {}
1564                             }
1565                         }
1566                     }
1567                     if found_pub_static {
1568                         intravisit::walk_generics(self, &impl_.generics)
1569                     }
1570                 }
1571                 return;
1572             }
1573
1574             // `type ... = ...;` can contain private types, because
1575             // we're introducing a new name.
1576             hir::ItemKind::TyAlias(..) => return,
1577
1578             // Not at all public, so we don't care.
1579             _ if !self.item_is_public(item.def_id) => {
1580                 return;
1581             }
1582
1583             _ => {}
1584         }
1585
1586         // We've carefully constructed it so that if we're here, then
1587         // any `visit_ty`'s will be called on things that are in
1588         // public signatures, i.e., things that we're interested in for
1589         // this visitor.
1590         intravisit::walk_item(self, item);
1591     }
1592
1593     fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1594         for predicate in generics.predicates {
1595             match predicate {
1596                 hir::WherePredicate::BoundPredicate(bound_pred) => {
1597                     for bound in bound_pred.bounds.iter() {
1598                         self.check_generic_bound(bound)
1599                     }
1600                 }
1601                 hir::WherePredicate::RegionPredicate(_) => {}
1602                 hir::WherePredicate::EqPredicate(eq_pred) => {
1603                     self.visit_ty(eq_pred.rhs_ty);
1604                 }
1605             }
1606         }
1607     }
1608
1609     fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
1610         if self.access_levels.is_reachable(item.def_id) {
1611             intravisit::walk_foreign_item(self, item)
1612         }
1613     }
1614
1615     fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
1616         if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = t.kind {
1617             if self.path_is_private_type(path) {
1618                 self.old_error_set.insert(t.hir_id);
1619             }
1620         }
1621         intravisit::walk_ty(self, t)
1622     }
1623
1624     fn visit_variant(
1625         &mut self,
1626         v: &'tcx hir::Variant<'tcx>,
1627         g: &'tcx hir::Generics<'tcx>,
1628         item_id: hir::HirId,
1629     ) {
1630         if self.access_levels.is_reachable(self.tcx.hir().local_def_id(v.id)) {
1631             self.in_variant = true;
1632             intravisit::walk_variant(self, v, g, item_id);
1633             self.in_variant = false;
1634         }
1635     }
1636
1637     fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) {
1638         let def_id = self.tcx.hir().local_def_id(s.hir_id);
1639         let vis = self.tcx.visibility(def_id);
1640         if vis.is_public() || self.in_variant {
1641             intravisit::walk_field_def(self, s);
1642         }
1643     }
1644
1645     // We don't need to introspect into these at all: an
1646     // expression/block context can't possibly contain exported things.
1647     // (Making them no-ops stops us from traversing the whole AST without
1648     // having to be super careful about our `walk_...` calls above.)
1649     fn visit_block(&mut self, _: &'tcx hir::Block<'tcx>) {}
1650     fn visit_expr(&mut self, _: &'tcx hir::Expr<'tcx>) {}
1651 }
1652
1653 ///////////////////////////////////////////////////////////////////////////////
1654 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1655 /// finds any private components in it.
1656 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1657 /// and traits in public interfaces.
1658 ///////////////////////////////////////////////////////////////////////////////
1659
1660 struct SearchInterfaceForPrivateItemsVisitor<'tcx> {
1661     tcx: TyCtxt<'tcx>,
1662     item_def_id: LocalDefId,
1663     /// The visitor checks that each component type is at least this visible.
1664     required_visibility: ty::Visibility,
1665     has_old_errors: bool,
1666     in_assoc_ty: bool,
1667 }
1668
1669 impl SearchInterfaceForPrivateItemsVisitor<'_> {
1670     fn generics(&mut self) -> &mut Self {
1671         for param in &self.tcx.generics_of(self.item_def_id).params {
1672             match param.kind {
1673                 GenericParamDefKind::Lifetime => {}
1674                 GenericParamDefKind::Type { has_default, .. } => {
1675                     if has_default {
1676                         self.visit(self.tcx.type_of(param.def_id));
1677                     }
1678                 }
1679                 // FIXME(generic_const_exprs): May want to look inside const here
1680                 GenericParamDefKind::Const { .. } => {
1681                     self.visit(self.tcx.type_of(param.def_id));
1682                 }
1683             }
1684         }
1685         self
1686     }
1687
1688     fn predicates(&mut self) -> &mut Self {
1689         // N.B., we use `explicit_predicates_of` and not `predicates_of`
1690         // because we don't want to report privacy errors due to where
1691         // clauses that the compiler inferred. We only want to
1692         // consider the ones that the user wrote. This is important
1693         // for the inferred outlives rules; see
1694         // `src/test/ui/rfc-2093-infer-outlives/privacy.rs`.
1695         self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id));
1696         self
1697     }
1698
1699     fn bounds(&mut self) -> &mut Self {
1700         self.visit_predicates(ty::GenericPredicates {
1701             parent: None,
1702             predicates: self.tcx.explicit_item_bounds(self.item_def_id),
1703         });
1704         self
1705     }
1706
1707     fn ty(&mut self) -> &mut Self {
1708         self.visit(self.tcx.type_of(self.item_def_id));
1709         self
1710     }
1711
1712     fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1713         if self.leaks_private_dep(def_id) {
1714             self.tcx.struct_span_lint_hir(
1715                 lint::builtin::EXPORTED_PRIVATE_DEPENDENCIES,
1716                 self.tcx.hir().local_def_id_to_hir_id(self.item_def_id),
1717                 self.tcx.def_span(self.item_def_id.to_def_id()),
1718                 |lint| {
1719                     lint.build(&format!(
1720                         "{} `{}` from private dependency '{}' in public \
1721                                                 interface",
1722                         kind,
1723                         descr,
1724                         self.tcx.crate_name(def_id.krate)
1725                     ))
1726                     .emit();
1727                 },
1728             );
1729         }
1730
1731         let hir_id = match def_id.as_local() {
1732             Some(def_id) => self.tcx.hir().local_def_id_to_hir_id(def_id),
1733             None => return false,
1734         };
1735
1736         let vis = self.tcx.visibility(def_id);
1737         if !vis.is_at_least(self.required_visibility, self.tcx) {
1738             let vis_descr = match vis {
1739                 ty::Visibility::Public => "public",
1740                 ty::Visibility::Invisible => "private",
1741                 ty::Visibility::Restricted(vis_def_id) => {
1742                     if vis_def_id == self.tcx.parent_module(hir_id).to_def_id() {
1743                         "private"
1744                     } else if vis_def_id.is_top_level_module() {
1745                         "crate-private"
1746                     } else {
1747                         "restricted"
1748                     }
1749                 }
1750             };
1751             let make_msg = || format!("{} {} `{}` in public interface", vis_descr, kind, descr);
1752             let span = self.tcx.def_span(self.item_def_id.to_def_id());
1753             if self.has_old_errors
1754                 || self.in_assoc_ty
1755                 || self.tcx.resolutions(()).has_pub_restricted
1756             {
1757                 let mut err = if kind == "trait" {
1758                     struct_span_err!(self.tcx.sess, span, E0445, "{}", make_msg())
1759                 } else {
1760                     struct_span_err!(self.tcx.sess, span, E0446, "{}", make_msg())
1761                 };
1762                 let vis_span =
1763                     self.tcx.sess.source_map().guess_head_span(self.tcx.def_span(def_id));
1764                 err.span_label(span, format!("can't leak {} {}", vis_descr, kind));
1765                 err.span_label(vis_span, format!("`{}` declared as {}", descr, vis_descr));
1766                 err.emit();
1767             } else {
1768                 let err_code = if kind == "trait" { "E0445" } else { "E0446" };
1769                 self.tcx.struct_span_lint_hir(
1770                     lint::builtin::PRIVATE_IN_PUBLIC,
1771                     hir_id,
1772                     span,
1773                     |lint| {
1774                         lint.build(&format!("{} (error {})", make_msg(), err_code)).emit();
1775                     },
1776                 );
1777             }
1778         }
1779
1780         false
1781     }
1782
1783     /// An item is 'leaked' from a private dependency if all
1784     /// of the following are true:
1785     /// 1. It's contained within a public type
1786     /// 2. It comes from a private crate
1787     fn leaks_private_dep(&self, item_id: DefId) -> bool {
1788         let ret = self.required_visibility.is_public() && self.tcx.is_private_dep(item_id.krate);
1789
1790         tracing::debug!("leaks_private_dep(item_id={:?})={}", item_id, ret);
1791         ret
1792     }
1793 }
1794
1795 impl<'tcx> DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> {
1796     fn tcx(&self) -> TyCtxt<'tcx> {
1797         self.tcx
1798     }
1799     fn visit_def_id(
1800         &mut self,
1801         def_id: DefId,
1802         kind: &str,
1803         descr: &dyn fmt::Display,
1804     ) -> ControlFlow<Self::BreakTy> {
1805         if self.check_def_id(def_id, kind, descr) {
1806             ControlFlow::BREAK
1807         } else {
1808             ControlFlow::CONTINUE
1809         }
1810     }
1811 }
1812
1813 struct PrivateItemsInPublicInterfacesChecker<'tcx> {
1814     tcx: TyCtxt<'tcx>,
1815     old_error_set_ancestry: LocalDefIdSet,
1816 }
1817
1818 impl<'tcx> PrivateItemsInPublicInterfacesChecker<'tcx> {
1819     fn check(
1820         &self,
1821         def_id: LocalDefId,
1822         required_visibility: ty::Visibility,
1823     ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> {
1824         SearchInterfaceForPrivateItemsVisitor {
1825             tcx: self.tcx,
1826             item_def_id: def_id,
1827             required_visibility,
1828             has_old_errors: self.old_error_set_ancestry.contains(&def_id),
1829             in_assoc_ty: false,
1830         }
1831     }
1832
1833     fn check_assoc_item(
1834         &self,
1835         def_id: LocalDefId,
1836         assoc_item_kind: AssocItemKind,
1837         defaultness: hir::Defaultness,
1838         vis: ty::Visibility,
1839     ) {
1840         let mut check = self.check(def_id, vis);
1841
1842         let (check_ty, is_assoc_ty) = match assoc_item_kind {
1843             AssocItemKind::Const | AssocItemKind::Fn { .. } => (true, false),
1844             AssocItemKind::Type => (defaultness.has_value(), true),
1845         };
1846         check.in_assoc_ty = is_assoc_ty;
1847         check.generics().predicates();
1848         if check_ty {
1849             check.ty();
1850         }
1851     }
1852
1853     pub fn check_item(&mut self, id: ItemId) {
1854         let tcx = self.tcx;
1855         let item_visibility = tcx.visibility(id.def_id);
1856         let def_kind = tcx.def_kind(id.def_id);
1857
1858         match def_kind {
1859             DefKind::Const | DefKind::Static(_) | DefKind::Fn | DefKind::TyAlias => {
1860                 self.check(id.def_id, item_visibility).generics().predicates().ty();
1861             }
1862             DefKind::OpaqueTy => {
1863                 // `ty()` for opaque types is the underlying type,
1864                 // it's not a part of interface, so we skip it.
1865                 self.check(id.def_id, item_visibility).generics().bounds();
1866             }
1867             DefKind::Trait => {
1868                 let item = tcx.hir().item(id);
1869                 if let hir::ItemKind::Trait(.., trait_item_refs) = item.kind {
1870                     self.check(item.def_id, item_visibility).generics().predicates();
1871
1872                     for trait_item_ref in trait_item_refs {
1873                         self.check_assoc_item(
1874                             trait_item_ref.id.def_id,
1875                             trait_item_ref.kind,
1876                             trait_item_ref.defaultness,
1877                             item_visibility,
1878                         );
1879
1880                         if let AssocItemKind::Type = trait_item_ref.kind {
1881                             self.check(trait_item_ref.id.def_id, item_visibility).bounds();
1882                         }
1883                     }
1884                 }
1885             }
1886             DefKind::TraitAlias => {
1887                 self.check(id.def_id, item_visibility).generics().predicates();
1888             }
1889             DefKind::Enum => {
1890                 let item = tcx.hir().item(id);
1891                 if let hir::ItemKind::Enum(ref def, _) = item.kind {
1892                     self.check(item.def_id, item_visibility).generics().predicates();
1893
1894                     for variant in def.variants {
1895                         for field in variant.data.fields() {
1896                             self.check(self.tcx.hir().local_def_id(field.hir_id), item_visibility)
1897                                 .ty();
1898                         }
1899                     }
1900                 }
1901             }
1902             // Subitems of foreign modules have their own publicity.
1903             DefKind::ForeignMod => {
1904                 let item = tcx.hir().item(id);
1905                 if let hir::ItemKind::ForeignMod { items, .. } = item.kind {
1906                     for foreign_item in items {
1907                         let vis = tcx.visibility(foreign_item.id.def_id);
1908                         self.check(foreign_item.id.def_id, vis).generics().predicates().ty();
1909                     }
1910                 }
1911             }
1912             // Subitems of structs and unions have their own publicity.
1913             DefKind::Struct | DefKind::Union => {
1914                 let item = tcx.hir().item(id);
1915                 if let hir::ItemKind::Struct(ref struct_def, _)
1916                 | hir::ItemKind::Union(ref struct_def, _) = item.kind
1917                 {
1918                     self.check(item.def_id, item_visibility).generics().predicates();
1919
1920                     for field in struct_def.fields() {
1921                         let def_id = tcx.hir().local_def_id(field.hir_id);
1922                         let field_visibility = tcx.visibility(def_id);
1923                         self.check(def_id, min(item_visibility, field_visibility, tcx)).ty();
1924                     }
1925                 }
1926             }
1927             // An inherent impl is public when its type is public
1928             // Subitems of inherent impls have their own publicity.
1929             // A trait impl is public when both its type and its trait are public
1930             // Subitems of trait impls have inherited publicity.
1931             DefKind::Impl => {
1932                 let item = tcx.hir().item(id);
1933                 if let hir::ItemKind::Impl(ref impl_) = item.kind {
1934                     let impl_vis = ty::Visibility::of_impl(item.def_id, tcx, &Default::default());
1935                     // check that private components do not appear in the generics or predicates of inherent impls
1936                     // this check is intentionally NOT performed for impls of traits, per #90586
1937                     if impl_.of_trait.is_none() {
1938                         self.check(item.def_id, impl_vis).generics().predicates();
1939                     }
1940                     for impl_item_ref in impl_.items {
1941                         let impl_item_vis = if impl_.of_trait.is_none() {
1942                             min(tcx.visibility(impl_item_ref.id.def_id), impl_vis, tcx)
1943                         } else {
1944                             impl_vis
1945                         };
1946                         self.check_assoc_item(
1947                             impl_item_ref.id.def_id,
1948                             impl_item_ref.kind,
1949                             impl_item_ref.defaultness,
1950                             impl_item_vis,
1951                         );
1952                     }
1953                 }
1954             }
1955             _ => {}
1956         }
1957     }
1958 }
1959
1960 pub fn provide(providers: &mut Providers) {
1961     *providers = Providers {
1962         visibility,
1963         privacy_access_levels,
1964         check_private_in_public,
1965         check_mod_privacy,
1966         ..*providers
1967     };
1968 }
1969
1970 fn visibility(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Visibility {
1971     let def_id = def_id.expect_local();
1972     match tcx.resolutions(()).visibilities.get(&def_id) {
1973         Some(vis) => *vis,
1974         None => {
1975             let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
1976             match tcx.hir().get(hir_id) {
1977                 // Unique types created for closures participate in type privacy checking.
1978                 // They have visibilities inherited from the module they are defined in.
1979                 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure{..}, .. })
1980                 // - AST lowering creates dummy `use` items which don't
1981                 //   get their entries in the resolver's visibility table.
1982                 // - AST lowering also creates opaque type items with inherited visibilities.
1983                 //   Visibility on them should have no effect, but to avoid the visibility
1984                 //   query failing on some items, we provide it for opaque types as well.
1985                 | Node::Item(hir::Item {
1986                     kind: hir::ItemKind::Use(_, hir::UseKind::ListStem) | hir::ItemKind::OpaqueTy(..),
1987                     ..
1988                 }) => ty::Visibility::Restricted(tcx.parent_module(hir_id).to_def_id()),
1989                 // Visibilities of trait impl items are inherited from their traits
1990                 // and are not filled in resolve.
1991                 Node::ImplItem(impl_item) => {
1992                     match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(hir_id)) {
1993                         Node::Item(hir::Item {
1994                             kind: hir::ItemKind::Impl(hir::Impl { of_trait: Some(tr), .. }),
1995                             ..
1996                         }) => tr.path.res.opt_def_id().map_or_else(
1997                             || {
1998                                 tcx.sess.delay_span_bug(tr.path.span, "trait without a def-id");
1999                                 ty::Visibility::Public
2000                             },
2001                             |def_id| tcx.visibility(def_id),
2002                         ),
2003                         _ => span_bug!(impl_item.span, "the parent is not a trait impl"),
2004                     }
2005                 }
2006                 _ => span_bug!(
2007                     tcx.def_span(def_id),
2008                     "visibility table unexpectedly missing a def-id: {:?}",
2009                     def_id,
2010                 ),
2011             }
2012         }
2013     }
2014 }
2015
2016 fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
2017     // Check privacy of names not checked in previous compilation stages.
2018     let mut visitor =
2019         NamePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id };
2020     let (module, span, hir_id) = tcx.hir().get_module(module_def_id);
2021
2022     intravisit::walk_mod(&mut visitor, module, hir_id);
2023
2024     // Check privacy of explicitly written types and traits as well as
2025     // inferred types of expressions and patterns.
2026     let mut visitor =
2027         TypePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id, span };
2028     intravisit::walk_mod(&mut visitor, module, hir_id);
2029 }
2030
2031 fn privacy_access_levels(tcx: TyCtxt<'_>, (): ()) -> &AccessLevels {
2032     // Build up a set of all exported items in the AST. This is a set of all
2033     // items which are reachable from external crates based on visibility.
2034     let mut visitor = EmbargoVisitor {
2035         tcx,
2036         access_levels: tcx.resolutions(()).access_levels.clone(),
2037         macro_reachable: Default::default(),
2038         prev_level: Some(AccessLevel::Public),
2039         changed: false,
2040     };
2041
2042     loop {
2043         tcx.hir().walk_toplevel_module(&mut visitor);
2044         if visitor.changed {
2045             visitor.changed = false;
2046         } else {
2047             break;
2048         }
2049     }
2050
2051     tcx.arena.alloc(visitor.access_levels)
2052 }
2053
2054 fn check_private_in_public(tcx: TyCtxt<'_>, (): ()) {
2055     let access_levels = tcx.privacy_access_levels(());
2056
2057     let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
2058         tcx,
2059         access_levels,
2060         in_variant: false,
2061         old_error_set: Default::default(),
2062     };
2063     tcx.hir().walk_toplevel_module(&mut visitor);
2064
2065     let mut old_error_set_ancestry = HirIdSet::default();
2066     for mut id in visitor.old_error_set.iter().copied() {
2067         loop {
2068             if !old_error_set_ancestry.insert(id) {
2069                 break;
2070             }
2071             let parent = tcx.hir().get_parent_node(id);
2072             if parent == id {
2073                 break;
2074             }
2075             id = parent;
2076         }
2077     }
2078
2079     // Check for private types and traits in public interfaces.
2080     let mut checker = PrivateItemsInPublicInterfacesChecker {
2081         tcx,
2082         // Only definition IDs are ever searched in `old_error_set_ancestry`,
2083         // so we can filter away all non-definition IDs at this point.
2084         old_error_set_ancestry: old_error_set_ancestry
2085             .into_iter()
2086             .filter_map(|hir_id| tcx.hir().opt_local_def_id(hir_id))
2087             .collect(),
2088     };
2089
2090     for id in tcx.hir().items() {
2091         checker.check_item(id);
2092     }
2093 }