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