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