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