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