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