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