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