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