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