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