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