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