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