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