]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_privacy/src/lib.rs
Rollup merge of #89270 - seanyoung:join_fold, r=m-ou-se
[rust.git] / compiler / rustc_privacy / src / lib.rs
1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
2 #![feature(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()
747                         || self.tcx.visibility(impl_item_ref.id.def_id) == ty::Visibility::Public
748                     {
749                         self.update(impl_item_ref.id.def_id, item_level);
750                     }
751                 }
752             }
753             hir::ItemKind::Trait(.., trait_item_refs) => {
754                 for trait_item_ref in trait_item_refs {
755                     self.update(trait_item_ref.id.def_id, item_level);
756                 }
757             }
758             hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => {
759                 if let Some(ctor_hir_id) = def.ctor_hir_id() {
760                     self.update(self.tcx.hir().local_def_id(ctor_hir_id), item_level);
761                 }
762                 for field in def.fields() {
763                     if field.vis.node.is_pub() {
764                         self.update(self.tcx.hir().local_def_id(field.hir_id), item_level);
765                     }
766                 }
767             }
768             hir::ItemKind::Macro(ref macro_def) => {
769                 self.update_reachability_from_macro(item.def_id, macro_def);
770             }
771             hir::ItemKind::ForeignMod { items, .. } => {
772                 for foreign_item in items {
773                     if self.tcx.visibility(foreign_item.id.def_id) == ty::Visibility::Public {
774                         self.update(foreign_item.id.def_id, item_level);
775                     }
776                 }
777             }
778
779             hir::ItemKind::OpaqueTy(..)
780             | hir::ItemKind::Use(..)
781             | hir::ItemKind::Static(..)
782             | hir::ItemKind::Const(..)
783             | hir::ItemKind::GlobalAsm(..)
784             | hir::ItemKind::TyAlias(..)
785             | hir::ItemKind::Mod(..)
786             | hir::ItemKind::TraitAlias(..)
787             | hir::ItemKind::Fn(..)
788             | hir::ItemKind::ExternCrate(..) => {}
789         }
790
791         // Mark all items in interfaces of reachable items as reachable.
792         match item.kind {
793             // The interface is empty.
794             hir::ItemKind::Macro(..) | hir::ItemKind::ExternCrate(..) => {}
795             // All nested items are checked by `visit_item`.
796             hir::ItemKind::Mod(..) => {}
797             // Re-exports are handled in `visit_mod`. However, in order to avoid looping over
798             // all of the items of a mod in `visit_mod` looking for use statements, we handle
799             // making sure that intermediate use statements have their visibilities updated here.
800             hir::ItemKind::Use(path, _) => {
801                 if item_level.is_some() {
802                     self.update_visibility_of_intermediate_use_statements(path.segments.as_ref());
803                 }
804             }
805             // The interface is empty.
806             hir::ItemKind::GlobalAsm(..) => {}
807             hir::ItemKind::OpaqueTy(..) => {
808                 // HACK(jynelson): trying to infer the type of `impl trait` breaks `async-std` (and `pub async fn` in general)
809                 // Since rustdoc never needs to do codegen and doesn't care about link-time reachability,
810                 // mark this as unreachable.
811                 // See https://github.com/rust-lang/rust/issues/75100
812                 if !self.tcx.sess.opts.actually_rustdoc {
813                     // FIXME: This is some serious pessimization intended to workaround deficiencies
814                     // in the reachability pass (`middle/reachable.rs`). Types are marked as link-time
815                     // reachable if they are returned via `impl Trait`, even from private functions.
816                     let exist_level =
817                         cmp::max(item_level, Some(AccessLevel::ReachableFromImplTrait));
818                     self.reach(item.def_id, exist_level).generics().predicates().ty();
819                 }
820             }
821             // Visit everything.
822             hir::ItemKind::Const(..)
823             | hir::ItemKind::Static(..)
824             | hir::ItemKind::Fn(..)
825             | hir::ItemKind::TyAlias(..) => {
826                 if item_level.is_some() {
827                     self.reach(item.def_id, item_level).generics().predicates().ty();
828                 }
829             }
830             hir::ItemKind::Trait(.., trait_item_refs) => {
831                 if item_level.is_some() {
832                     self.reach(item.def_id, item_level).generics().predicates();
833
834                     for trait_item_ref in trait_item_refs {
835                         let mut reach = self.reach(trait_item_ref.id.def_id, item_level);
836                         reach.generics().predicates();
837
838                         if trait_item_ref.kind == AssocItemKind::Type
839                             && !trait_item_ref.defaultness.has_value()
840                         {
841                             // No type to visit.
842                         } else {
843                             reach.ty();
844                         }
845                     }
846                 }
847             }
848             hir::ItemKind::TraitAlias(..) => {
849                 if item_level.is_some() {
850                     self.reach(item.def_id, item_level).generics().predicates();
851                 }
852             }
853             // Visit everything except for private impl items.
854             hir::ItemKind::Impl(ref impl_) => {
855                 if item_level.is_some() {
856                     self.reach(item.def_id, item_level).generics().predicates().ty().trait_ref();
857
858                     for impl_item_ref in impl_.items {
859                         let impl_item_level = self.get(impl_item_ref.id.def_id);
860                         if impl_item_level.is_some() {
861                             self.reach(impl_item_ref.id.def_id, impl_item_level)
862                                 .generics()
863                                 .predicates()
864                                 .ty();
865                         }
866                     }
867                 }
868             }
869
870             // Visit everything, but enum variants have their own levels.
871             hir::ItemKind::Enum(ref def, _) => {
872                 if item_level.is_some() {
873                     self.reach(item.def_id, item_level).generics().predicates();
874                 }
875                 for variant in def.variants {
876                     let variant_level = self.get(self.tcx.hir().local_def_id(variant.id));
877                     if variant_level.is_some() {
878                         for field in variant.data.fields() {
879                             self.reach(self.tcx.hir().local_def_id(field.hir_id), variant_level)
880                                 .ty();
881                         }
882                         // Corner case: if the variant is reachable, but its
883                         // enum is not, make the enum reachable as well.
884                         self.update(item.def_id, variant_level);
885                     }
886                 }
887             }
888             // Visit everything, but foreign items have their own levels.
889             hir::ItemKind::ForeignMod { items, .. } => {
890                 for foreign_item in items {
891                     let foreign_item_level = self.get(foreign_item.id.def_id);
892                     if foreign_item_level.is_some() {
893                         self.reach(foreign_item.id.def_id, foreign_item_level)
894                             .generics()
895                             .predicates()
896                             .ty();
897                     }
898                 }
899             }
900             // Visit everything except for private fields.
901             hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
902                 if item_level.is_some() {
903                     self.reach(item.def_id, item_level).generics().predicates();
904                     for field in struct_def.fields() {
905                         let def_id = self.tcx.hir().local_def_id(field.hir_id);
906                         let field_level = self.get(def_id);
907                         if field_level.is_some() {
908                             self.reach(def_id, field_level).ty();
909                         }
910                     }
911                 }
912             }
913         }
914
915         let orig_level = mem::replace(&mut self.prev_level, item_level);
916         intravisit::walk_item(self, item);
917         self.prev_level = orig_level;
918     }
919
920     fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
921         // Blocks can have public items, for example impls, but they always
922         // start as completely private regardless of publicity of a function,
923         // constant, type, field, etc., in which this block resides.
924         let orig_level = mem::replace(&mut self.prev_level, None);
925         intravisit::walk_block(self, b);
926         self.prev_level = orig_level;
927     }
928
929     fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, _sp: Span, id: hir::HirId) {
930         // This code is here instead of in visit_item so that the
931         // crate module gets processed as well.
932         if self.prev_level.is_some() {
933             let def_id = self.tcx.hir().local_def_id(id);
934             if let Some(exports) = self.tcx.module_exports(def_id) {
935                 for export in exports.iter() {
936                     if export.vis == ty::Visibility::Public {
937                         if let Some(def_id) = export.res.opt_def_id() {
938                             if let Some(def_id) = def_id.as_local() {
939                                 self.update(def_id, Some(AccessLevel::Exported));
940                             }
941                         }
942                     }
943                 }
944             }
945         }
946
947         intravisit::walk_mod(self, m, id);
948     }
949 }
950
951 impl ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
952     fn generics(&mut self) -> &mut Self {
953         for param in &self.ev.tcx.generics_of(self.item_def_id).params {
954             match param.kind {
955                 GenericParamDefKind::Lifetime => {}
956                 GenericParamDefKind::Type { has_default, .. } => {
957                     if has_default {
958                         self.visit(self.ev.tcx.type_of(param.def_id));
959                     }
960                 }
961                 GenericParamDefKind::Const { has_default, .. } => {
962                     self.visit(self.ev.tcx.type_of(param.def_id));
963                     if has_default {
964                         self.visit(self.ev.tcx.const_param_default(param.def_id));
965                     }
966                 }
967             }
968         }
969         self
970     }
971
972     fn predicates(&mut self) -> &mut Self {
973         self.visit_predicates(self.ev.tcx.predicates_of(self.item_def_id));
974         self
975     }
976
977     fn ty(&mut self) -> &mut Self {
978         self.visit(self.ev.tcx.type_of(self.item_def_id));
979         self
980     }
981
982     fn trait_ref(&mut self) -> &mut Self {
983         if let Some(trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) {
984             self.visit_trait(trait_ref);
985         }
986         self
987     }
988 }
989
990 impl DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
991     fn tcx(&self) -> TyCtxt<'tcx> {
992         self.ev.tcx
993     }
994     fn visit_def_id(
995         &mut self,
996         def_id: DefId,
997         _kind: &str,
998         _descr: &dyn fmt::Display,
999     ) -> ControlFlow<Self::BreakTy> {
1000         if let Some(def_id) = def_id.as_local() {
1001             if let (ty::Visibility::Public, _) | (_, Some(AccessLevel::ReachableFromImplTrait)) =
1002                 (self.tcx().visibility(def_id.to_def_id()), self.access_level)
1003             {
1004                 self.ev.update(def_id, self.access_level);
1005             }
1006         }
1007         ControlFlow::CONTINUE
1008     }
1009 }
1010
1011 //////////////////////////////////////////////////////////////////////////////////////
1012 /// Name privacy visitor, checks privacy and reports violations.
1013 /// Most of name privacy checks are performed during the main resolution phase,
1014 /// or later in type checking when field accesses and associated items are resolved.
1015 /// This pass performs remaining checks for fields in struct expressions and patterns.
1016 //////////////////////////////////////////////////////////////////////////////////////
1017
1018 struct NamePrivacyVisitor<'tcx> {
1019     tcx: TyCtxt<'tcx>,
1020     maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
1021     current_item: LocalDefId,
1022 }
1023
1024 impl<'tcx> NamePrivacyVisitor<'tcx> {
1025     /// Gets the type-checking results for the current body.
1026     /// As this will ICE if called outside bodies, only call when working with
1027     /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
1028     #[track_caller]
1029     fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
1030         self.maybe_typeck_results
1031             .expect("`NamePrivacyVisitor::typeck_results` called outside of body")
1032     }
1033
1034     // Checks that a field in a struct constructor (expression or pattern) is accessible.
1035     fn check_field(
1036         &mut self,
1037         use_ctxt: Span,        // syntax context of the field name at the use site
1038         span: Span,            // span of the field pattern, e.g., `x: 0`
1039         def: &'tcx ty::AdtDef, // definition of the struct or enum
1040         field: &'tcx ty::FieldDef,
1041         in_update_syntax: bool,
1042     ) {
1043         if def.is_enum() {
1044             return;
1045         }
1046
1047         // definition of the field
1048         let ident = Ident::new(kw::Empty, use_ctxt);
1049         let hir_id = self.tcx.hir().local_def_id_to_hir_id(self.current_item);
1050         let def_id = self.tcx.adjust_ident_and_get_scope(ident, def.did, hir_id).1;
1051         if !field.vis.is_accessible_from(def_id, self.tcx) {
1052             let label = if in_update_syntax {
1053                 format!("field `{}` is private", field.ident)
1054             } else {
1055                 "private field".to_string()
1056             };
1057
1058             struct_span_err!(
1059                 self.tcx.sess,
1060                 span,
1061                 E0451,
1062                 "field `{}` of {} `{}` is private",
1063                 field.ident,
1064                 def.variant_descr(),
1065                 self.tcx.def_path_str(def.did)
1066             )
1067             .span_label(span, label)
1068             .emit();
1069         }
1070     }
1071 }
1072
1073 impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> {
1074     type Map = Map<'tcx>;
1075
1076     /// We want to visit items in the context of their containing
1077     /// module and so forth, so supply a crate for doing a deep walk.
1078     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1079         NestedVisitorMap::All(self.tcx.hir())
1080     }
1081
1082     fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) {
1083         // Don't visit nested modules, since we run a separate visitor walk
1084         // for each module in `privacy_access_levels`
1085     }
1086
1087     fn visit_nested_body(&mut self, body: hir::BodyId) {
1088         let old_maybe_typeck_results =
1089             self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
1090         let body = self.tcx.hir().body(body);
1091         self.visit_body(body);
1092         self.maybe_typeck_results = old_maybe_typeck_results;
1093     }
1094
1095     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1096         let orig_current_item = mem::replace(&mut self.current_item, item.def_id);
1097         intravisit::walk_item(self, item);
1098         self.current_item = orig_current_item;
1099     }
1100
1101     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1102         if let hir::ExprKind::Struct(qpath, fields, ref base) = expr.kind {
1103             let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
1104             let adt = self.typeck_results().expr_ty(expr).ty_adt_def().unwrap();
1105             let variant = adt.variant_of_res(res);
1106             if let Some(base) = *base {
1107                 // If the expression uses FRU we need to make sure all the unmentioned fields
1108                 // are checked for privacy (RFC 736). Rather than computing the set of
1109                 // unmentioned fields, just check them all.
1110                 for (vf_index, variant_field) in variant.fields.iter().enumerate() {
1111                     let field = fields.iter().find(|f| {
1112                         self.tcx.field_index(f.hir_id, self.typeck_results()) == vf_index
1113                     });
1114                     let (use_ctxt, span) = match field {
1115                         Some(field) => (field.ident.span, field.span),
1116                         None => (base.span, base.span),
1117                     };
1118                     self.check_field(use_ctxt, span, adt, variant_field, true);
1119                 }
1120             } else {
1121                 for field in fields {
1122                     let use_ctxt = field.ident.span;
1123                     let index = self.tcx.field_index(field.hir_id, self.typeck_results());
1124                     self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false);
1125                 }
1126             }
1127         }
1128
1129         intravisit::walk_expr(self, expr);
1130     }
1131
1132     fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
1133         if let PatKind::Struct(ref qpath, fields, _) = pat.kind {
1134             let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
1135             let adt = self.typeck_results().pat_ty(pat).ty_adt_def().unwrap();
1136             let variant = adt.variant_of_res(res);
1137             for field in fields {
1138                 let use_ctxt = field.ident.span;
1139                 let index = self.tcx.field_index(field.hir_id, self.typeck_results());
1140                 self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false);
1141             }
1142         }
1143
1144         intravisit::walk_pat(self, pat);
1145     }
1146 }
1147
1148 ////////////////////////////////////////////////////////////////////////////////////////////
1149 /// Type privacy visitor, checks types for privacy and reports violations.
1150 /// Both explicitly written types and inferred types of expressions and patterns are checked.
1151 /// Checks are performed on "semantic" types regardless of names and their hygiene.
1152 ////////////////////////////////////////////////////////////////////////////////////////////
1153
1154 struct TypePrivacyVisitor<'tcx> {
1155     tcx: TyCtxt<'tcx>,
1156     maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
1157     current_item: LocalDefId,
1158     span: Span,
1159 }
1160
1161 impl<'tcx> TypePrivacyVisitor<'tcx> {
1162     /// Gets the type-checking results for the current body.
1163     /// As this will ICE if called outside bodies, only call when working with
1164     /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
1165     #[track_caller]
1166     fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
1167         self.maybe_typeck_results
1168             .expect("`TypePrivacyVisitor::typeck_results` called outside of body")
1169     }
1170
1171     fn item_is_accessible(&self, did: DefId) -> bool {
1172         self.tcx.visibility(did).is_accessible_from(self.current_item.to_def_id(), self.tcx)
1173     }
1174
1175     // Take node-id of an expression or pattern and check its type for privacy.
1176     fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
1177         self.span = span;
1178         let typeck_results = self.typeck_results();
1179         let result: ControlFlow<()> = try {
1180             self.visit(typeck_results.node_type(id))?;
1181             self.visit(typeck_results.node_substs(id))?;
1182             if let Some(adjustments) = typeck_results.adjustments().get(id) {
1183                 adjustments.iter().try_for_each(|adjustment| self.visit(adjustment.target))?;
1184             }
1185         };
1186         result.is_break()
1187     }
1188
1189     fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1190         let is_error = !self.item_is_accessible(def_id);
1191         if is_error {
1192             self.tcx
1193                 .sess
1194                 .struct_span_err(self.span, &format!("{} `{}` is private", kind, descr))
1195                 .span_label(self.span, &format!("private {}", kind))
1196                 .emit();
1197         }
1198         is_error
1199     }
1200 }
1201
1202 impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> {
1203     type Map = Map<'tcx>;
1204
1205     /// We want to visit items in the context of their containing
1206     /// module and so forth, so supply a crate for doing a deep walk.
1207     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1208         NestedVisitorMap::All(self.tcx.hir())
1209     }
1210
1211     fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) {
1212         // Don't visit nested modules, since we run a separate visitor walk
1213         // for each module in `privacy_access_levels`
1214     }
1215
1216     fn visit_nested_body(&mut self, body: hir::BodyId) {
1217         let old_maybe_typeck_results =
1218             self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
1219         let body = self.tcx.hir().body(body);
1220         self.visit_body(body);
1221         self.maybe_typeck_results = old_maybe_typeck_results;
1222     }
1223
1224     fn visit_generic_arg(&mut self, generic_arg: &'tcx hir::GenericArg<'tcx>) {
1225         match generic_arg {
1226             hir::GenericArg::Type(t) => self.visit_ty(t),
1227             hir::GenericArg::Infer(inf) => self.visit_infer(inf),
1228             hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {}
1229         }
1230     }
1231
1232     fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) {
1233         self.span = hir_ty.span;
1234         if let Some(typeck_results) = self.maybe_typeck_results {
1235             // Types in bodies.
1236             if self.visit(typeck_results.node_type(hir_ty.hir_id)).is_break() {
1237                 return;
1238             }
1239         } else {
1240             // Types in signatures.
1241             // FIXME: This is very ineffective. Ideally each HIR type should be converted
1242             // into a semantic type only once and the result should be cached somehow.
1243             if self.visit(rustc_typeck::hir_ty_to_ty(self.tcx, hir_ty)).is_break() {
1244                 return;
1245             }
1246         }
1247
1248         intravisit::walk_ty(self, hir_ty);
1249     }
1250
1251     fn visit_infer(&mut self, inf: &'tcx hir::InferArg) {
1252         self.span = inf.span;
1253         if let Some(typeck_results) = self.maybe_typeck_results {
1254             if let Some(ty) = typeck_results.node_type_opt(inf.hir_id) {
1255                 if self.visit(ty).is_break() {
1256                     return;
1257                 }
1258             }
1259         } else {
1260             let local_id = self.tcx.hir().local_def_id(inf.hir_id);
1261             if let Some(did) = self.tcx.opt_const_param_of(local_id) {
1262                 if self.visit_def_id(did, "inferred", &"").is_break() {
1263                     return;
1264                 }
1265             }
1266
1267             // FIXME see above note for same issue.
1268             if self.visit(rustc_typeck::hir_ty_to_ty(self.tcx, &inf.to_ty())).is_break() {
1269                 return;
1270             }
1271         }
1272         intravisit::walk_inf(self, inf);
1273     }
1274
1275     fn visit_trait_ref(&mut self, trait_ref: &'tcx hir::TraitRef<'tcx>) {
1276         self.span = trait_ref.path.span;
1277         if self.maybe_typeck_results.is_none() {
1278             // Avoid calling `hir_trait_to_predicates` in bodies, it will ICE.
1279             // The traits' privacy in bodies is already checked as a part of trait object types.
1280             let bounds = rustc_typeck::hir_trait_to_predicates(
1281                 self.tcx,
1282                 trait_ref,
1283                 // NOTE: This isn't really right, but the actual type doesn't matter here. It's
1284                 // just required by `ty::TraitRef`.
1285                 self.tcx.types.never,
1286             );
1287
1288             for (trait_predicate, _, _) in bounds.trait_bounds {
1289                 if self.visit_trait(trait_predicate.skip_binder()).is_break() {
1290                     return;
1291                 }
1292             }
1293
1294             for (poly_predicate, _) in bounds.projection_bounds {
1295                 if self.visit(poly_predicate.skip_binder().ty).is_break()
1296                     || self
1297                         .visit_projection_ty(poly_predicate.skip_binder().projection_ty)
1298                         .is_break()
1299                 {
1300                     return;
1301                 }
1302             }
1303         }
1304
1305         intravisit::walk_trait_ref(self, trait_ref);
1306     }
1307
1308     // Check types of expressions
1309     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1310         if self.check_expr_pat_type(expr.hir_id, expr.span) {
1311             // Do not check nested expressions if the error already happened.
1312             return;
1313         }
1314         match expr.kind {
1315             hir::ExprKind::Assign(_, rhs, _) | hir::ExprKind::Match(rhs, ..) => {
1316                 // Do not report duplicate errors for `x = y` and `match x { ... }`.
1317                 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
1318                     return;
1319                 }
1320             }
1321             hir::ExprKind::MethodCall(_, span, _, _) => {
1322                 // Method calls have to be checked specially.
1323                 self.span = span;
1324                 if let Some(def_id) = self.typeck_results().type_dependent_def_id(expr.hir_id) {
1325                     if self.visit(self.tcx.type_of(def_id)).is_break() {
1326                         return;
1327                     }
1328                 } else {
1329                     self.tcx
1330                         .sess
1331                         .delay_span_bug(expr.span, "no type-dependent def for method call");
1332                 }
1333             }
1334             _ => {}
1335         }
1336
1337         intravisit::walk_expr(self, expr);
1338     }
1339
1340     // Prohibit access to associated items with insufficient nominal visibility.
1341     //
1342     // Additionally, until better reachability analysis for macros 2.0 is available,
1343     // we prohibit access to private statics from other crates, this allows to give
1344     // more code internal visibility at link time. (Access to private functions
1345     // is already prohibited by type privacy for function types.)
1346     fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) {
1347         let def = match qpath {
1348             hir::QPath::Resolved(_, path) => match path.res {
1349                 Res::Def(kind, def_id) => Some((kind, def_id)),
1350                 _ => None,
1351             },
1352             hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self
1353                 .maybe_typeck_results
1354                 .and_then(|typeck_results| typeck_results.type_dependent_def(id)),
1355         };
1356         let def = def.filter(|(kind, _)| {
1357             matches!(
1358                 kind,
1359                 DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static
1360             )
1361         });
1362         if let Some((kind, def_id)) = def {
1363             let is_local_static =
1364                 if let DefKind::Static = kind { def_id.is_local() } else { false };
1365             if !self.item_is_accessible(def_id) && !is_local_static {
1366                 let sess = self.tcx.sess;
1367                 let sm = sess.source_map();
1368                 let name = match qpath {
1369                     hir::QPath::Resolved(..) | hir::QPath::LangItem(..) => {
1370                         sm.span_to_snippet(qpath.span()).ok()
1371                     }
1372                     hir::QPath::TypeRelative(_, segment) => Some(segment.ident.to_string()),
1373                 };
1374                 let kind = kind.descr(def_id);
1375                 let msg = match name {
1376                     Some(name) => format!("{} `{}` is private", kind, name),
1377                     None => format!("{} is private", kind),
1378                 };
1379                 sess.struct_span_err(span, &msg)
1380                     .span_label(span, &format!("private {}", kind))
1381                     .emit();
1382                 return;
1383             }
1384         }
1385
1386         intravisit::walk_qpath(self, qpath, id, span);
1387     }
1388
1389     // Check types of patterns.
1390     fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) {
1391         if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
1392             // Do not check nested patterns if the error already happened.
1393             return;
1394         }
1395
1396         intravisit::walk_pat(self, pattern);
1397     }
1398
1399     fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) {
1400         if let Some(init) = local.init {
1401             if self.check_expr_pat_type(init.hir_id, init.span) {
1402                 // Do not report duplicate errors for `let x = y`.
1403                 return;
1404             }
1405         }
1406
1407         intravisit::walk_local(self, local);
1408     }
1409
1410     // Check types in item interfaces.
1411     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1412         let orig_current_item = mem::replace(&mut self.current_item, item.def_id);
1413         let old_maybe_typeck_results = self.maybe_typeck_results.take();
1414         intravisit::walk_item(self, item);
1415         self.maybe_typeck_results = old_maybe_typeck_results;
1416         self.current_item = orig_current_item;
1417     }
1418 }
1419
1420 impl DefIdVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1421     fn tcx(&self) -> TyCtxt<'tcx> {
1422         self.tcx
1423     }
1424     fn visit_def_id(
1425         &mut self,
1426         def_id: DefId,
1427         kind: &str,
1428         descr: &dyn fmt::Display,
1429     ) -> ControlFlow<Self::BreakTy> {
1430         if self.check_def_id(def_id, kind, descr) {
1431             ControlFlow::BREAK
1432         } else {
1433             ControlFlow::CONTINUE
1434         }
1435     }
1436 }
1437
1438 ///////////////////////////////////////////////////////////////////////////////
1439 /// Obsolete visitors for checking for private items in public interfaces.
1440 /// These visitors are supposed to be kept in frozen state and produce an
1441 /// "old error node set". For backward compatibility the new visitor reports
1442 /// warnings instead of hard errors when the erroneous node is not in this old set.
1443 ///////////////////////////////////////////////////////////////////////////////
1444
1445 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1446     tcx: TyCtxt<'tcx>,
1447     access_levels: &'a AccessLevels,
1448     in_variant: bool,
1449     // Set of errors produced by this obsolete visitor.
1450     old_error_set: HirIdSet,
1451 }
1452
1453 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1454     inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
1455     /// Whether the type refers to private types.
1456     contains_private: bool,
1457     /// Whether we've recurred at all (i.e., if we're pointing at the
1458     /// first type on which `visit_ty` was called).
1459     at_outer_type: bool,
1460     /// Whether that first type is a public path.
1461     outer_type_is_public_path: bool,
1462 }
1463
1464 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1465     fn path_is_private_type(&self, path: &hir::Path<'_>) -> bool {
1466         let did = match path.res {
1467             Res::PrimTy(..) | Res::SelfTy(..) | Res::Err => return false,
1468             res => res.def_id(),
1469         };
1470
1471         // A path can only be private if:
1472         // it's in this crate...
1473         if let Some(did) = did.as_local() {
1474             // .. and it corresponds to a private type in the AST (this returns
1475             // `None` for type parameters).
1476             match self.tcx.hir().find(self.tcx.hir().local_def_id_to_hir_id(did)) {
1477                 Some(Node::Item(item)) => !item.vis.node.is_pub(),
1478                 Some(_) | None => false,
1479             }
1480         } else {
1481             false
1482         }
1483     }
1484
1485     fn trait_is_public(&self, trait_id: LocalDefId) -> bool {
1486         // FIXME: this would preferably be using `exported_items`, but all
1487         // traits are exported currently (see `EmbargoVisitor.exported_trait`).
1488         self.access_levels.is_public(trait_id)
1489     }
1490
1491     fn check_generic_bound(&mut self, bound: &hir::GenericBound<'_>) {
1492         if let hir::GenericBound::Trait(ref trait_ref, _) = *bound {
1493             if self.path_is_private_type(trait_ref.trait_ref.path) {
1494                 self.old_error_set.insert(trait_ref.trait_ref.hir_ref_id);
1495             }
1496         }
1497     }
1498
1499     fn item_is_public(&self, def_id: LocalDefId, vis: &hir::Visibility<'_>) -> bool {
1500         self.access_levels.is_reachable(def_id) || vis.node.is_pub()
1501     }
1502 }
1503
1504 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1505     type Map = intravisit::ErasedMap<'v>;
1506
1507     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1508         NestedVisitorMap::None
1509     }
1510
1511     fn visit_generic_arg(&mut self, generic_arg: &'v hir::GenericArg<'v>) {
1512         match generic_arg {
1513             hir::GenericArg::Type(t) => self.visit_ty(t),
1514             hir::GenericArg::Infer(inf) => self.visit_ty(&inf.to_ty()),
1515             hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {}
1516         }
1517     }
1518
1519     fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
1520         if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = ty.kind {
1521             if self.inner.path_is_private_type(path) {
1522                 self.contains_private = true;
1523                 // Found what we're looking for, so let's stop working.
1524                 return;
1525             }
1526         }
1527         if let hir::TyKind::Path(_) = ty.kind {
1528             if self.at_outer_type {
1529                 self.outer_type_is_public_path = true;
1530             }
1531         }
1532         self.at_outer_type = false;
1533         intravisit::walk_ty(self, ty)
1534     }
1535
1536     // Don't want to recurse into `[, .. expr]`.
1537     fn visit_expr(&mut self, _: &hir::Expr<'_>) {}
1538 }
1539
1540 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1541     type Map = Map<'tcx>;
1542
1543     /// We want to visit items in the context of their containing
1544     /// module and so forth, so supply a crate for doing a deep walk.
1545     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1546         NestedVisitorMap::All(self.tcx.hir())
1547     }
1548
1549     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1550         match item.kind {
1551             // Contents of a private mod can be re-exported, so we need
1552             // to check internals.
1553             hir::ItemKind::Mod(_) => {}
1554
1555             // An `extern {}` doesn't introduce a new privacy
1556             // namespace (the contents have their own privacies).
1557             hir::ItemKind::ForeignMod { .. } => {}
1558
1559             hir::ItemKind::Trait(.., bounds, _) => {
1560                 if !self.trait_is_public(item.def_id) {
1561                     return;
1562                 }
1563
1564                 for bound in bounds.iter() {
1565                     self.check_generic_bound(bound)
1566                 }
1567             }
1568
1569             // Impls need some special handling to try to offer useful
1570             // error messages without (too many) false positives
1571             // (i.e., we could just return here to not check them at
1572             // all, or some worse estimation of whether an impl is
1573             // publicly visible).
1574             hir::ItemKind::Impl(ref impl_) => {
1575                 // `impl [... for] Private` is never visible.
1576                 let self_contains_private;
1577                 // `impl [... for] Public<...>`, but not `impl [... for]
1578                 // Vec<Public>` or `(Public,)`, etc.
1579                 let self_is_public_path;
1580
1581                 // Check the properties of the `Self` type:
1582                 {
1583                     let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
1584                         inner: self,
1585                         contains_private: false,
1586                         at_outer_type: true,
1587                         outer_type_is_public_path: false,
1588                     };
1589                     visitor.visit_ty(impl_.self_ty);
1590                     self_contains_private = visitor.contains_private;
1591                     self_is_public_path = visitor.outer_type_is_public_path;
1592                 }
1593
1594                 // Miscellaneous info about the impl:
1595
1596                 // `true` iff this is `impl Private for ...`.
1597                 let not_private_trait = impl_.of_trait.as_ref().map_or(
1598                     true, // no trait counts as public trait
1599                     |tr| {
1600                         if let Some(def_id) = tr.path.res.def_id().as_local() {
1601                             self.trait_is_public(def_id)
1602                         } else {
1603                             true // external traits must be public
1604                         }
1605                     },
1606                 );
1607
1608                 // `true` iff this is a trait impl or at least one method is public.
1609                 //
1610                 // `impl Public { $( fn ...() {} )* }` is not visible.
1611                 //
1612                 // This is required over just using the methods' privacy
1613                 // directly because we might have `impl<T: Foo<Private>> ...`,
1614                 // and we shouldn't warn about the generics if all the methods
1615                 // are private (because `T` won't be visible externally).
1616                 let trait_or_some_public_method = impl_.of_trait.is_some()
1617                     || impl_.items.iter().any(|impl_item_ref| {
1618                         let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1619                         match impl_item.kind {
1620                             hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) => {
1621                                 self.access_levels.is_reachable(impl_item_ref.id.def_id)
1622                             }
1623                             hir::ImplItemKind::TyAlias(_) => false,
1624                         }
1625                     });
1626
1627                 if !self_contains_private && not_private_trait && trait_or_some_public_method {
1628                     intravisit::walk_generics(self, &impl_.generics);
1629
1630                     match impl_.of_trait {
1631                         None => {
1632                             for impl_item_ref in impl_.items {
1633                                 // This is where we choose whether to walk down
1634                                 // further into the impl to check its items. We
1635                                 // should only walk into public items so that we
1636                                 // don't erroneously report errors for private
1637                                 // types in private items.
1638                                 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1639                                 match impl_item.kind {
1640                                     hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..)
1641                                         if self
1642                                             .item_is_public(impl_item.def_id, &impl_item.vis) =>
1643                                     {
1644                                         intravisit::walk_impl_item(self, impl_item)
1645                                     }
1646                                     hir::ImplItemKind::TyAlias(..) => {
1647                                         intravisit::walk_impl_item(self, impl_item)
1648                                     }
1649                                     _ => {}
1650                                 }
1651                             }
1652                         }
1653                         Some(ref tr) => {
1654                             // Any private types in a trait impl fall into three
1655                             // categories.
1656                             // 1. mentioned in the trait definition
1657                             // 2. mentioned in the type params/generics
1658                             // 3. mentioned in the associated types of the impl
1659                             //
1660                             // Those in 1. can only occur if the trait is in
1661                             // this crate and will've been warned about on the
1662                             // trait definition (there's no need to warn twice
1663                             // so we don't check the methods).
1664                             //
1665                             // Those in 2. are warned via walk_generics and this
1666                             // call here.
1667                             intravisit::walk_path(self, tr.path);
1668
1669                             // Those in 3. are warned with this call.
1670                             for impl_item_ref in impl_.items {
1671                                 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1672                                 if let hir::ImplItemKind::TyAlias(ty) = impl_item.kind {
1673                                     self.visit_ty(ty);
1674                                 }
1675                             }
1676                         }
1677                     }
1678                 } else if impl_.of_trait.is_none() && self_is_public_path {
1679                     // `impl Public<Private> { ... }`. Any public static
1680                     // methods will be visible as `Public::foo`.
1681                     let mut found_pub_static = false;
1682                     for impl_item_ref in impl_.items {
1683                         if self.access_levels.is_reachable(impl_item_ref.id.def_id)
1684                             || self.tcx.visibility(impl_item_ref.id.def_id)
1685                                 == ty::Visibility::Public
1686                         {
1687                             let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1688                             match impl_item_ref.kind {
1689                                 AssocItemKind::Const => {
1690                                     found_pub_static = true;
1691                                     intravisit::walk_impl_item(self, impl_item);
1692                                 }
1693                                 AssocItemKind::Fn { has_self: false } => {
1694                                     found_pub_static = true;
1695                                     intravisit::walk_impl_item(self, impl_item);
1696                                 }
1697                                 _ => {}
1698                             }
1699                         }
1700                     }
1701                     if found_pub_static {
1702                         intravisit::walk_generics(self, &impl_.generics)
1703                     }
1704                 }
1705                 return;
1706             }
1707
1708             // `type ... = ...;` can contain private types, because
1709             // we're introducing a new name.
1710             hir::ItemKind::TyAlias(..) => return,
1711
1712             // Not at all public, so we don't care.
1713             _ if !self.item_is_public(item.def_id, &item.vis) => {
1714                 return;
1715             }
1716
1717             _ => {}
1718         }
1719
1720         // We've carefully constructed it so that if we're here, then
1721         // any `visit_ty`'s will be called on things that are in
1722         // public signatures, i.e., things that we're interested in for
1723         // this visitor.
1724         intravisit::walk_item(self, item);
1725     }
1726
1727     fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1728         for param in generics.params {
1729             for bound in param.bounds {
1730                 self.check_generic_bound(bound);
1731             }
1732         }
1733         for predicate in generics.where_clause.predicates {
1734             match predicate {
1735                 hir::WherePredicate::BoundPredicate(bound_pred) => {
1736                     for bound in bound_pred.bounds.iter() {
1737                         self.check_generic_bound(bound)
1738                     }
1739                 }
1740                 hir::WherePredicate::RegionPredicate(_) => {}
1741                 hir::WherePredicate::EqPredicate(eq_pred) => {
1742                     self.visit_ty(eq_pred.rhs_ty);
1743                 }
1744             }
1745         }
1746     }
1747
1748     fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) {
1749         if self.access_levels.is_reachable(item.def_id) {
1750             intravisit::walk_foreign_item(self, item)
1751         }
1752     }
1753
1754     fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) {
1755         if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = t.kind {
1756             if self.path_is_private_type(path) {
1757                 self.old_error_set.insert(t.hir_id);
1758             }
1759         }
1760         intravisit::walk_ty(self, t)
1761     }
1762
1763     fn visit_variant(
1764         &mut self,
1765         v: &'tcx hir::Variant<'tcx>,
1766         g: &'tcx hir::Generics<'tcx>,
1767         item_id: hir::HirId,
1768     ) {
1769         if self.access_levels.is_reachable(self.tcx.hir().local_def_id(v.id)) {
1770             self.in_variant = true;
1771             intravisit::walk_variant(self, v, g, item_id);
1772             self.in_variant = false;
1773         }
1774     }
1775
1776     fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) {
1777         if s.vis.node.is_pub() || self.in_variant {
1778             intravisit::walk_field_def(self, s);
1779         }
1780     }
1781
1782     // We don't need to introspect into these at all: an
1783     // expression/block context can't possibly contain exported things.
1784     // (Making them no-ops stops us from traversing the whole AST without
1785     // having to be super careful about our `walk_...` calls above.)
1786     fn visit_block(&mut self, _: &'tcx hir::Block<'tcx>) {}
1787     fn visit_expr(&mut self, _: &'tcx hir::Expr<'tcx>) {}
1788 }
1789
1790 ///////////////////////////////////////////////////////////////////////////////
1791 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1792 /// finds any private components in it.
1793 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1794 /// and traits in public interfaces.
1795 ///////////////////////////////////////////////////////////////////////////////
1796
1797 struct SearchInterfaceForPrivateItemsVisitor<'tcx> {
1798     tcx: TyCtxt<'tcx>,
1799     item_def_id: LocalDefId,
1800     /// The visitor checks that each component type is at least this visible.
1801     required_visibility: ty::Visibility,
1802     has_pub_restricted: bool,
1803     has_old_errors: bool,
1804     in_assoc_ty: bool,
1805 }
1806
1807 impl SearchInterfaceForPrivateItemsVisitor<'tcx> {
1808     fn generics(&mut self) -> &mut Self {
1809         for param in &self.tcx.generics_of(self.item_def_id).params {
1810             match param.kind {
1811                 GenericParamDefKind::Lifetime => {}
1812                 GenericParamDefKind::Type { has_default, .. } => {
1813                     if has_default {
1814                         self.visit(self.tcx.type_of(param.def_id));
1815                     }
1816                 }
1817                 // FIXME(generic_const_exprs): May want to look inside const here
1818                 GenericParamDefKind::Const { .. } => {
1819                     self.visit(self.tcx.type_of(param.def_id));
1820                 }
1821             }
1822         }
1823         self
1824     }
1825
1826     fn predicates(&mut self) -> &mut Self {
1827         // N.B., we use `explicit_predicates_of` and not `predicates_of`
1828         // because we don't want to report privacy errors due to where
1829         // clauses that the compiler inferred. We only want to
1830         // consider the ones that the user wrote. This is important
1831         // for the inferred outlives rules; see
1832         // `src/test/ui/rfc-2093-infer-outlives/privacy.rs`.
1833         self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id));
1834         self
1835     }
1836
1837     fn bounds(&mut self) -> &mut Self {
1838         self.visit_predicates(ty::GenericPredicates {
1839             parent: None,
1840             predicates: self.tcx.explicit_item_bounds(self.item_def_id),
1841         });
1842         self
1843     }
1844
1845     fn ty(&mut self) -> &mut Self {
1846         self.visit(self.tcx.type_of(self.item_def_id));
1847         self
1848     }
1849
1850     fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1851         if self.leaks_private_dep(def_id) {
1852             self.tcx.struct_span_lint_hir(
1853                 lint::builtin::EXPORTED_PRIVATE_DEPENDENCIES,
1854                 self.tcx.hir().local_def_id_to_hir_id(self.item_def_id),
1855                 self.tcx.def_span(self.item_def_id.to_def_id()),
1856                 |lint| {
1857                     lint.build(&format!(
1858                         "{} `{}` from private dependency '{}' in public \
1859                                                 interface",
1860                         kind,
1861                         descr,
1862                         self.tcx.crate_name(def_id.krate)
1863                     ))
1864                     .emit()
1865                 },
1866             );
1867         }
1868
1869         let hir_id = match def_id.as_local() {
1870             Some(def_id) => self.tcx.hir().local_def_id_to_hir_id(def_id),
1871             None => return false,
1872         };
1873
1874         let vis = self.tcx.visibility(def_id);
1875         if !vis.is_at_least(self.required_visibility, self.tcx) {
1876             let vis_descr = match vis {
1877                 ty::Visibility::Public => "public",
1878                 ty::Visibility::Invisible => "private",
1879                 ty::Visibility::Restricted(vis_def_id) => {
1880                     if vis_def_id == self.tcx.parent_module(hir_id).to_def_id() {
1881                         "private"
1882                     } else if vis_def_id.is_top_level_module() {
1883                         "crate-private"
1884                     } else {
1885                         "restricted"
1886                     }
1887                 }
1888             };
1889             let make_msg = || format!("{} {} `{}` in public interface", vis_descr, kind, descr);
1890             let span = self.tcx.def_span(self.item_def_id.to_def_id());
1891             if self.has_pub_restricted || self.has_old_errors || self.in_assoc_ty {
1892                 let mut err = if kind == "trait" {
1893                     struct_span_err!(self.tcx.sess, span, E0445, "{}", make_msg())
1894                 } else {
1895                     struct_span_err!(self.tcx.sess, span, E0446, "{}", make_msg())
1896                 };
1897                 let vis_span =
1898                     self.tcx.sess.source_map().guess_head_span(self.tcx.def_span(def_id));
1899                 err.span_label(span, format!("can't leak {} {}", vis_descr, kind));
1900                 err.span_label(vis_span, format!("`{}` declared as {}", descr, vis_descr));
1901                 err.emit();
1902             } else {
1903                 let err_code = if kind == "trait" { "E0445" } else { "E0446" };
1904                 self.tcx.struct_span_lint_hir(
1905                     lint::builtin::PRIVATE_IN_PUBLIC,
1906                     hir_id,
1907                     span,
1908                     |lint| lint.build(&format!("{} (error {})", make_msg(), err_code)).emit(),
1909                 );
1910             }
1911         }
1912
1913         false
1914     }
1915
1916     /// An item is 'leaked' from a private dependency if all
1917     /// of the following are true:
1918     /// 1. It's contained within a public type
1919     /// 2. It comes from a private crate
1920     fn leaks_private_dep(&self, item_id: DefId) -> bool {
1921         let ret = self.required_visibility == ty::Visibility::Public
1922             && self.tcx.is_private_dep(item_id.krate);
1923
1924         tracing::debug!("leaks_private_dep(item_id={:?})={}", item_id, ret);
1925         ret
1926     }
1927 }
1928
1929 impl DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> {
1930     fn tcx(&self) -> TyCtxt<'tcx> {
1931         self.tcx
1932     }
1933     fn visit_def_id(
1934         &mut self,
1935         def_id: DefId,
1936         kind: &str,
1937         descr: &dyn fmt::Display,
1938     ) -> ControlFlow<Self::BreakTy> {
1939         if self.check_def_id(def_id, kind, descr) {
1940             ControlFlow::BREAK
1941         } else {
1942             ControlFlow::CONTINUE
1943         }
1944     }
1945 }
1946
1947 struct PrivateItemsInPublicInterfacesVisitor<'tcx> {
1948     tcx: TyCtxt<'tcx>,
1949     has_pub_restricted: bool,
1950     old_error_set_ancestry: LocalDefIdSet,
1951 }
1952
1953 impl<'tcx> PrivateItemsInPublicInterfacesVisitor<'tcx> {
1954     fn check(
1955         &self,
1956         def_id: LocalDefId,
1957         required_visibility: ty::Visibility,
1958     ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> {
1959         SearchInterfaceForPrivateItemsVisitor {
1960             tcx: self.tcx,
1961             item_def_id: def_id,
1962             required_visibility,
1963             has_pub_restricted: self.has_pub_restricted,
1964             has_old_errors: self.old_error_set_ancestry.contains(&def_id),
1965             in_assoc_ty: false,
1966         }
1967     }
1968
1969     fn check_assoc_item(
1970         &self,
1971         def_id: LocalDefId,
1972         assoc_item_kind: AssocItemKind,
1973         defaultness: hir::Defaultness,
1974         vis: ty::Visibility,
1975     ) {
1976         let mut check = self.check(def_id, vis);
1977
1978         let (check_ty, is_assoc_ty) = match assoc_item_kind {
1979             AssocItemKind::Const | AssocItemKind::Fn { .. } => (true, false),
1980             AssocItemKind::Type => (defaultness.has_value(), true),
1981         };
1982         check.in_assoc_ty = is_assoc_ty;
1983         check.generics().predicates();
1984         if check_ty {
1985             check.ty();
1986         }
1987     }
1988 }
1989
1990 impl<'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'tcx> {
1991     type Map = Map<'tcx>;
1992
1993     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1994         NestedVisitorMap::OnlyBodies(self.tcx.hir())
1995     }
1996
1997     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1998         let tcx = self.tcx;
1999         let item_visibility = tcx.visibility(item.def_id);
2000
2001         match item.kind {
2002             // Crates are always public.
2003             hir::ItemKind::ExternCrate(..) => {}
2004             // All nested items are checked by `visit_item`.
2005             hir::ItemKind::Mod(..) => {}
2006             // Checked in resolve.
2007             hir::ItemKind::Use(..) => {}
2008             // No subitems.
2009             hir::ItemKind::Macro(..) | hir::ItemKind::GlobalAsm(..) => {}
2010             // Subitems of these items have inherited publicity.
2011             hir::ItemKind::Const(..)
2012             | hir::ItemKind::Static(..)
2013             | hir::ItemKind::Fn(..)
2014             | hir::ItemKind::TyAlias(..) => {
2015                 self.check(item.def_id, item_visibility).generics().predicates().ty();
2016             }
2017             hir::ItemKind::OpaqueTy(..) => {
2018                 // `ty()` for opaque types is the underlying type,
2019                 // it's not a part of interface, so we skip it.
2020                 self.check(item.def_id, item_visibility).generics().bounds();
2021             }
2022             hir::ItemKind::Trait(.., trait_item_refs) => {
2023                 self.check(item.def_id, item_visibility).generics().predicates();
2024
2025                 for trait_item_ref in trait_item_refs {
2026                     self.check_assoc_item(
2027                         trait_item_ref.id.def_id,
2028                         trait_item_ref.kind,
2029                         trait_item_ref.defaultness,
2030                         item_visibility,
2031                     );
2032
2033                     if let AssocItemKind::Type = trait_item_ref.kind {
2034                         self.check(trait_item_ref.id.def_id, item_visibility).bounds();
2035                     }
2036                 }
2037             }
2038             hir::ItemKind::TraitAlias(..) => {
2039                 self.check(item.def_id, item_visibility).generics().predicates();
2040             }
2041             hir::ItemKind::Enum(ref def, _) => {
2042                 self.check(item.def_id, item_visibility).generics().predicates();
2043
2044                 for variant in def.variants {
2045                     for field in variant.data.fields() {
2046                         self.check(self.tcx.hir().local_def_id(field.hir_id), item_visibility).ty();
2047                     }
2048                 }
2049             }
2050             // Subitems of foreign modules have their own publicity.
2051             hir::ItemKind::ForeignMod { items, .. } => {
2052                 for foreign_item in items {
2053                     let vis = tcx.visibility(foreign_item.id.def_id);
2054                     self.check(foreign_item.id.def_id, vis).generics().predicates().ty();
2055                 }
2056             }
2057             // Subitems of structs and unions have their own publicity.
2058             hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => {
2059                 self.check(item.def_id, item_visibility).generics().predicates();
2060
2061                 for field in struct_def.fields() {
2062                     let def_id = tcx.hir().local_def_id(field.hir_id);
2063                     let field_visibility = tcx.visibility(def_id);
2064                     self.check(def_id, min(item_visibility, field_visibility, tcx)).ty();
2065                 }
2066             }
2067             // An inherent impl is public when its type is public
2068             // Subitems of inherent impls have their own publicity.
2069             // A trait impl is public when both its type and its trait are public
2070             // Subitems of trait impls have inherited publicity.
2071             hir::ItemKind::Impl(ref impl_) => {
2072                 let impl_vis = ty::Visibility::of_impl(item.def_id, tcx, &Default::default());
2073                 self.check(item.def_id, impl_vis).generics().predicates();
2074                 for impl_item_ref in impl_.items {
2075                     let impl_item_vis = if impl_.of_trait.is_none() {
2076                         min(tcx.visibility(impl_item_ref.id.def_id), impl_vis, tcx)
2077                     } else {
2078                         impl_vis
2079                     };
2080                     self.check_assoc_item(
2081                         impl_item_ref.id.def_id,
2082                         impl_item_ref.kind,
2083                         impl_item_ref.defaultness,
2084                         impl_item_vis,
2085                     );
2086                 }
2087             }
2088         }
2089     }
2090 }
2091
2092 pub fn provide(providers: &mut Providers) {
2093     *providers = Providers {
2094         visibility,
2095         privacy_access_levels,
2096         check_private_in_public,
2097         check_mod_privacy,
2098         ..*providers
2099     };
2100 }
2101
2102 fn visibility(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Visibility {
2103     let def_id = def_id.expect_local();
2104     match tcx.resolutions(()).visibilities.get(&def_id) {
2105         Some(vis) => *vis,
2106         None => {
2107             let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
2108             match tcx.hir().get(hir_id) {
2109                 // Unique types created for closures participate in type privacy checking.
2110                 // They have visibilities inherited from the module they are defined in.
2111                 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => {
2112                     ty::Visibility::Restricted(tcx.parent_module(hir_id).to_def_id())
2113                 }
2114                 // - AST lowering may clone `use` items and the clones don't
2115                 //   get their entries in the resolver's visibility table.
2116                 // - AST lowering also creates opaque type items with inherited visibilies.
2117                 //   Visibility on them should have no effect, but to avoid the visibility
2118                 //   query failing on some items, we provide it for opaque types as well.
2119                 Node::Item(hir::Item {
2120                     vis,
2121                     kind: hir::ItemKind::Use(..) | hir::ItemKind::OpaqueTy(..),
2122                     ..
2123                 }) => ty::Visibility::from_hir(vis, hir_id, tcx),
2124                 // Visibilities of trait impl items are inherited from their traits
2125                 // and are not filled in resolve.
2126                 Node::ImplItem(impl_item) => {
2127                     match tcx.hir().get(tcx.hir().get_parent_item(hir_id)) {
2128                         Node::Item(hir::Item {
2129                             kind: hir::ItemKind::Impl(hir::Impl { of_trait: Some(tr), .. }),
2130                             ..
2131                         }) => tr.path.res.opt_def_id().map_or_else(
2132                             || {
2133                                 tcx.sess.delay_span_bug(tr.path.span, "trait without a def-id");
2134                                 ty::Visibility::Public
2135                             },
2136                             |def_id| tcx.visibility(def_id),
2137                         ),
2138                         _ => span_bug!(impl_item.span, "the parent is not a trait impl"),
2139                     }
2140                 }
2141                 _ => span_bug!(
2142                     tcx.def_span(def_id),
2143                     "visibility table unexpectedly missing a def-id: {:?}",
2144                     def_id,
2145                 ),
2146             }
2147         }
2148     }
2149 }
2150
2151 fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
2152     // Check privacy of names not checked in previous compilation stages.
2153     let mut visitor =
2154         NamePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id };
2155     let (module, span, hir_id) = tcx.hir().get_module(module_def_id);
2156
2157     intravisit::walk_mod(&mut visitor, module, hir_id);
2158
2159     // Check privacy of explicitly written types and traits as well as
2160     // inferred types of expressions and patterns.
2161     let mut visitor =
2162         TypePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id, span };
2163     intravisit::walk_mod(&mut visitor, module, hir_id);
2164 }
2165
2166 fn privacy_access_levels(tcx: TyCtxt<'_>, (): ()) -> &AccessLevels {
2167     // Build up a set of all exported items in the AST. This is a set of all
2168     // items which are reachable from external crates based on visibility.
2169     let mut visitor = EmbargoVisitor {
2170         tcx,
2171         access_levels: Default::default(),
2172         macro_reachable: Default::default(),
2173         prev_level: Some(AccessLevel::Public),
2174         changed: false,
2175     };
2176     loop {
2177         tcx.hir().walk_toplevel_module(&mut visitor);
2178         if visitor.changed {
2179             visitor.changed = false;
2180         } else {
2181             break;
2182         }
2183     }
2184     visitor.update(CRATE_DEF_ID, Some(AccessLevel::Public));
2185
2186     tcx.arena.alloc(visitor.access_levels)
2187 }
2188
2189 fn check_private_in_public(tcx: TyCtxt<'_>, (): ()) {
2190     let access_levels = tcx.privacy_access_levels(());
2191
2192     let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
2193         tcx,
2194         access_levels,
2195         in_variant: false,
2196         old_error_set: Default::default(),
2197     };
2198     tcx.hir().walk_toplevel_module(&mut visitor);
2199
2200     let has_pub_restricted = {
2201         let mut pub_restricted_visitor = PubRestrictedVisitor { tcx, has_pub_restricted: false };
2202         tcx.hir().walk_toplevel_module(&mut pub_restricted_visitor);
2203         pub_restricted_visitor.has_pub_restricted
2204     };
2205
2206     let mut old_error_set_ancestry = HirIdSet::default();
2207     for mut id in visitor.old_error_set.iter().copied() {
2208         loop {
2209             if !old_error_set_ancestry.insert(id) {
2210                 break;
2211             }
2212             let parent = tcx.hir().get_parent_node(id);
2213             if parent == id {
2214                 break;
2215             }
2216             id = parent;
2217         }
2218     }
2219
2220     // Check for private types and traits in public interfaces.
2221     let mut visitor = PrivateItemsInPublicInterfacesVisitor {
2222         tcx,
2223         has_pub_restricted,
2224         // Only definition IDs are ever searched in `old_error_set_ancestry`,
2225         // so we can filter away all non-definition IDs at this point.
2226         old_error_set_ancestry: old_error_set_ancestry
2227             .into_iter()
2228             .filter_map(|hir_id| tcx.hir().opt_local_def_id(hir_id))
2229             .collect(),
2230     };
2231     tcx.hir().visit_all_item_likes(&mut DeepVisitor::new(&mut visitor));
2232 }