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