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