]> git.lizzy.rs Git - rust.git/blob - src/librustc_privacy/lib.rs
1bdc22b37d73b804409a27052d716ad0d8696057
[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 impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> {
443     /// We want to visit items in the context of their containing
444     /// module and so forth, so supply a crate for doing a deep walk.
445     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
446         NestedVisitorMap::All(&self.tcx.hir())
447     }
448
449     fn visit_item(&mut self, item: &'tcx hir::Item) {
450         let inherited_item_level = match item.node {
451             hir::ItemKind::Impl(..) =>
452                 Option::<AccessLevel>::of_impl(item.id, self.tcx, &self.access_levels),
453             // Foreign modules inherit level from parents.
454             hir::ItemKind::ForeignMod(..) => self.prev_level,
455             // Other `pub` items inherit levels from parents.
456             hir::ItemKind::Const(..) | hir::ItemKind::Enum(..) | hir::ItemKind::ExternCrate(..) |
457             hir::ItemKind::GlobalAsm(..) | hir::ItemKind::Fn(..) | hir::ItemKind::Mod(..) |
458             hir::ItemKind::Static(..) | hir::ItemKind::Struct(..) |
459             hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) |
460             hir::ItemKind::Existential(..) |
461             hir::ItemKind::Ty(..) | hir::ItemKind::Union(..) | hir::ItemKind::Use(..) => {
462                 if item.vis.node.is_pub() { self.prev_level } else { None }
463             }
464         };
465
466         // Update level of the item itself.
467         let item_level = self.update(item.id, inherited_item_level);
468
469         // Update levels of nested things.
470         match item.node {
471             hir::ItemKind::Enum(ref def, _) => {
472                 for variant in &def.variants {
473                     let variant_level = self.update(variant.node.data.id(), item_level);
474                     for field in variant.node.data.fields() {
475                         self.update(field.id, variant_level);
476                     }
477                 }
478             }
479             hir::ItemKind::Impl(.., ref trait_ref, _, ref impl_item_refs) => {
480                 for impl_item_ref in impl_item_refs {
481                     if trait_ref.is_some() || impl_item_ref.vis.node.is_pub() {
482                         self.update(impl_item_ref.id.node_id, item_level);
483                     }
484                 }
485             }
486             hir::ItemKind::Trait(.., ref trait_item_refs) => {
487                 for trait_item_ref in trait_item_refs {
488                     self.update(trait_item_ref.id.node_id, item_level);
489                 }
490             }
491             hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => {
492                 if !def.is_struct() {
493                     self.update(def.id(), item_level);
494                 }
495                 for field in def.fields() {
496                     if field.vis.node.is_pub() {
497                         self.update(field.id, item_level);
498                     }
499                 }
500             }
501             hir::ItemKind::ForeignMod(ref foreign_mod) => {
502                 for foreign_item in &foreign_mod.items {
503                     if foreign_item.vis.node.is_pub() {
504                         self.update(foreign_item.id, item_level);
505                     }
506                 }
507             }
508             hir::ItemKind::Existential(..) |
509             hir::ItemKind::Use(..) |
510             hir::ItemKind::Static(..) |
511             hir::ItemKind::Const(..) |
512             hir::ItemKind::GlobalAsm(..) |
513             hir::ItemKind::Ty(..) |
514             hir::ItemKind::Mod(..) |
515             hir::ItemKind::TraitAlias(..) |
516             hir::ItemKind::Fn(..) |
517             hir::ItemKind::ExternCrate(..) => {}
518         }
519
520         // Mark all items in interfaces of reachable items as reachable.
521         match item.node {
522             // The interface is empty.
523             hir::ItemKind::ExternCrate(..) => {}
524             // All nested items are checked by `visit_item`.
525             hir::ItemKind::Mod(..) => {}
526             // Re-exports are handled in `visit_mod`.
527             hir::ItemKind::Use(..) => {}
528             // The interface is empty.
529             hir::ItemKind::GlobalAsm(..) => {}
530             hir::ItemKind::Existential(..) => {
531                 // FIXME: This is some serious pessimization intended to workaround deficiencies
532                 // in the reachability pass (`middle/reachable.rs`). Types are marked as link-time
533                 // reachable if they are returned via `impl Trait`, even from private functions.
534                 let exist_level = cmp::max(item_level, Some(AccessLevel::ReachableFromImplTrait));
535                 self.reach(item.id, exist_level).generics().predicates().ty();
536             }
537             // Visit everything.
538             hir::ItemKind::Const(..) | hir::ItemKind::Static(..) |
539             hir::ItemKind::Fn(..) | hir::ItemKind::Ty(..) => {
540                 if item_level.is_some() {
541                     self.reach(item.id, item_level).generics().predicates().ty();
542                 }
543             }
544             hir::ItemKind::Trait(.., ref trait_item_refs) => {
545                 if item_level.is_some() {
546                     self.reach(item.id, item_level).generics().predicates();
547
548                     for trait_item_ref in trait_item_refs {
549                         let mut reach = self.reach(trait_item_ref.id.node_id, item_level);
550                         reach.generics().predicates();
551
552                         if trait_item_ref.kind == AssociatedItemKind::Type &&
553                            !trait_item_ref.defaultness.has_value() {
554                             // No type to visit.
555                         } else {
556                             reach.ty();
557                         }
558                     }
559                 }
560             }
561             hir::ItemKind::TraitAlias(..) => {
562                 if item_level.is_some() {
563                     self.reach(item.id, item_level).generics().predicates();
564                 }
565             }
566             // Visit everything except for private impl items.
567             hir::ItemKind::Impl(.., ref impl_item_refs) => {
568                 if item_level.is_some() {
569                     self.reach(item.id, item_level).generics().predicates().ty().trait_ref();
570
571                     for impl_item_ref in impl_item_refs {
572                         let impl_item_level = self.get(impl_item_ref.id.node_id);
573                         if impl_item_level.is_some() {
574                             self.reach(impl_item_ref.id.node_id, impl_item_level)
575                                 .generics().predicates().ty();
576                         }
577                     }
578                 }
579             }
580
581             // Visit everything, but enum variants have their own levels.
582             hir::ItemKind::Enum(ref def, _) => {
583                 if item_level.is_some() {
584                     self.reach(item.id, item_level).generics().predicates();
585                 }
586                 for variant in &def.variants {
587                     let variant_level = self.get(variant.node.data.id());
588                     if variant_level.is_some() {
589                         for field in variant.node.data.fields() {
590                             self.reach(field.id, variant_level).ty();
591                         }
592                         // Corner case: if the variant is reachable, but its
593                         // enum is not, make the enum reachable as well.
594                         self.update(item.id, variant_level);
595                     }
596                 }
597             }
598             // Visit everything, but foreign items have their own levels.
599             hir::ItemKind::ForeignMod(ref foreign_mod) => {
600                 for foreign_item in &foreign_mod.items {
601                     let foreign_item_level = self.get(foreign_item.id);
602                     if foreign_item_level.is_some() {
603                         self.reach(foreign_item.id, foreign_item_level)
604                             .generics().predicates().ty();
605                     }
606                 }
607             }
608             // Visit everything except for private fields.
609             hir::ItemKind::Struct(ref struct_def, _) |
610             hir::ItemKind::Union(ref struct_def, _) => {
611                 if item_level.is_some() {
612                     self.reach(item.id, item_level).generics().predicates();
613                     for field in struct_def.fields() {
614                         let field_level = self.get(field.id);
615                         if field_level.is_some() {
616                             self.reach(field.id, field_level).ty();
617                         }
618                     }
619                 }
620             }
621         }
622
623         let orig_level = mem::replace(&mut self.prev_level, item_level);
624         intravisit::walk_item(self, item);
625         self.prev_level = orig_level;
626     }
627
628     fn visit_block(&mut self, b: &'tcx hir::Block) {
629         // Blocks can have public items, for example impls, but they always
630         // start as completely private regardless of publicity of a function,
631         // constant, type, field, etc., in which this block resides.
632         let orig_level = mem::replace(&mut self.prev_level, None);
633         intravisit::walk_block(self, b);
634         self.prev_level = orig_level;
635     }
636
637     fn visit_mod(&mut self, m: &'tcx hir::Mod, _sp: Span, id: ast::NodeId) {
638         // This code is here instead of in visit_item so that the
639         // crate module gets processed as well.
640         if self.prev_level.is_some() {
641             let def_id = self.tcx.hir().local_def_id(id);
642             if let Some(exports) = self.tcx.module_exports(def_id) {
643                 for export in exports.iter() {
644                     if export.vis == ty::Visibility::Public {
645                         if let Some(def_id) = export.def.opt_def_id() {
646                             if let Some(node_id) = self.tcx.hir().as_local_node_id(def_id) {
647                                 self.update(node_id, Some(AccessLevel::Exported));
648                             }
649                         }
650                     }
651                 }
652             }
653         }
654
655         intravisit::walk_mod(self, m, id);
656     }
657
658     fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef) {
659         if md.legacy {
660             self.update(md.id, Some(AccessLevel::Public));
661             return
662         }
663
664         let module_did = ty::DefIdTree::parent(
665             self.tcx,
666             self.tcx.hir().local_def_id(md.id)
667         ).unwrap();
668         let mut module_id = self.tcx.hir().as_local_node_id(module_did).unwrap();
669         let level = if md.vis.node.is_pub() { self.get(module_id) } else { None };
670         let level = self.update(md.id, level);
671         if level.is_none() {
672             return
673         }
674
675         loop {
676             let module = if module_id == ast::CRATE_NODE_ID {
677                 &self.tcx.hir().krate().module
678             } else if let hir::ItemKind::Mod(ref module) =
679                           self.tcx.hir().expect_item(module_id).node {
680                 module
681             } else {
682                 unreachable!()
683             };
684             for id in &module.item_ids {
685                 self.update(id.id, level);
686             }
687             let def_id = self.tcx.hir().local_def_id(module_id);
688             if let Some(exports) = self.tcx.module_exports(def_id) {
689                 for export in exports.iter() {
690                     if let Some(node_id) = self.tcx.hir().as_local_node_id(export.def.def_id()) {
691                         self.update(node_id, level);
692                     }
693                 }
694             }
695
696             if module_id == ast::CRATE_NODE_ID {
697                 break
698             }
699             module_id = self.tcx.hir().get_parent_node(module_id);
700         }
701     }
702 }
703
704 impl<'a, 'tcx> ReachEverythingInTheInterfaceVisitor<'_, 'a, 'tcx> {
705     fn generics(&mut self) -> &mut Self {
706         for param in &self.ev.tcx.generics_of(self.item_def_id).params {
707             match param.kind {
708                 GenericParamDefKind::Type { has_default, .. } => {
709                     if has_default {
710                         self.visit(self.ev.tcx.type_of(param.def_id));
711                     }
712                 }
713                 GenericParamDefKind::Lifetime => {}
714             }
715         }
716         self
717     }
718
719     fn predicates(&mut self) -> &mut Self {
720         self.visit_predicates(self.ev.tcx.predicates_of(self.item_def_id));
721         self
722     }
723
724     fn ty(&mut self) -> &mut Self {
725         self.visit(self.ev.tcx.type_of(self.item_def_id));
726         self
727     }
728
729     fn trait_ref(&mut self) -> &mut Self {
730         if let Some(trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) {
731             self.visit_trait(trait_ref);
732         }
733         self
734     }
735 }
736
737 impl<'a, 'tcx> DefIdVisitor<'a, 'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'a, 'tcx> {
738     fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.ev.tcx }
739     fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) -> bool {
740         if let Some(node_id) = self.ev.tcx.hir().as_local_node_id(def_id) {
741             self.ev.update(node_id, self.access_level);
742         }
743         false
744     }
745 }
746
747 //////////////////////////////////////////////////////////////////////////////////////
748 /// Name privacy visitor, checks privacy and reports violations.
749 /// Most of name privacy checks are performed during the main resolution phase,
750 /// or later in type checking when field accesses and associated items are resolved.
751 /// This pass performs remaining checks for fields in struct expressions and patterns.
752 //////////////////////////////////////////////////////////////////////////////////////
753
754 struct NamePrivacyVisitor<'a, 'tcx: 'a> {
755     tcx: TyCtxt<'a, 'tcx, 'tcx>,
756     tables: &'a ty::TypeckTables<'tcx>,
757     current_item: ast::NodeId,
758     empty_tables: &'a ty::TypeckTables<'tcx>,
759 }
760
761 impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> {
762     // Checks that a field in a struct constructor (expression or pattern) is accessible.
763     fn check_field(&mut self,
764                    use_ctxt: Span, // syntax context of the field name at the use site
765                    span: Span, // span of the field pattern, e.g., `x: 0`
766                    def: &'tcx ty::AdtDef, // definition of the struct or enum
767                    field: &'tcx ty::FieldDef) { // definition of the field
768         let ident = Ident::new(keywords::Invalid.name(), use_ctxt);
769         let def_id = self.tcx.adjust_ident(ident, def.did, self.current_item).1;
770         if !def.is_enum() && !field.vis.is_accessible_from(def_id, self.tcx) {
771             struct_span_err!(self.tcx.sess, span, E0451, "field `{}` of {} `{}` is private",
772                              field.ident, def.variant_descr(), self.tcx.item_path_str(def.did))
773                 .span_label(span, format!("field `{}` is private", field.ident))
774                 .emit();
775         }
776     }
777 }
778
779 impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> {
780     /// We want to visit items in the context of their containing
781     /// module and so forth, so supply a crate for doing a deep walk.
782     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
783         NestedVisitorMap::All(&self.tcx.hir())
784     }
785
786     fn visit_mod(&mut self, _m: &'tcx hir::Mod, _s: Span, _n: ast::NodeId) {
787         // Don't visit nested modules, since we run a separate visitor walk
788         // for each module in `privacy_access_levels`
789     }
790
791     fn visit_nested_body(&mut self, body: hir::BodyId) {
792         let orig_tables = mem::replace(&mut self.tables, self.tcx.body_tables(body));
793         let body = self.tcx.hir().body(body);
794         self.visit_body(body);
795         self.tables = orig_tables;
796     }
797
798     fn visit_item(&mut self, item: &'tcx hir::Item) {
799         let orig_current_item = mem::replace(&mut self.current_item, item.id);
800         let orig_tables =
801             mem::replace(&mut self.tables, item_tables(self.tcx, item.id, self.empty_tables));
802         intravisit::walk_item(self, item);
803         self.current_item = orig_current_item;
804         self.tables = orig_tables;
805     }
806
807     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
808         let orig_tables =
809             mem::replace(&mut self.tables, item_tables(self.tcx, ti.id, self.empty_tables));
810         intravisit::walk_trait_item(self, ti);
811         self.tables = orig_tables;
812     }
813
814     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
815         let orig_tables =
816             mem::replace(&mut self.tables, item_tables(self.tcx, ii.id, self.empty_tables));
817         intravisit::walk_impl_item(self, ii);
818         self.tables = orig_tables;
819     }
820
821     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
822         match expr.node {
823             hir::ExprKind::Struct(ref qpath, ref fields, ref base) => {
824                 let def = self.tables.qpath_def(qpath, expr.hir_id);
825                 let adt = self.tables.expr_ty(expr).ty_adt_def().unwrap();
826                 let variant = adt.variant_of_def(def);
827                 if let Some(ref base) = *base {
828                     // If the expression uses FRU we need to make sure all the unmentioned fields
829                     // are checked for privacy (RFC 736). Rather than computing the set of
830                     // unmentioned fields, just check them all.
831                     for (vf_index, variant_field) in variant.fields.iter().enumerate() {
832                         let field = fields.iter().find(|f| {
833                             self.tcx.field_index(f.id, self.tables) == vf_index
834                         });
835                         let (use_ctxt, span) = match field {
836                             Some(field) => (field.ident.span, field.span),
837                             None => (base.span, base.span),
838                         };
839                         self.check_field(use_ctxt, span, adt, variant_field);
840                     }
841                 } else {
842                     for field in fields {
843                         let use_ctxt = field.ident.span;
844                         let index = self.tcx.field_index(field.id, self.tables);
845                         self.check_field(use_ctxt, field.span, adt, &variant.fields[index]);
846                     }
847                 }
848             }
849             _ => {}
850         }
851
852         intravisit::walk_expr(self, expr);
853     }
854
855     fn visit_pat(&mut self, pat: &'tcx hir::Pat) {
856         match pat.node {
857             PatKind::Struct(ref qpath, ref fields, _) => {
858                 let def = self.tables.qpath_def(qpath, pat.hir_id);
859                 let adt = self.tables.pat_ty(pat).ty_adt_def().unwrap();
860                 let variant = adt.variant_of_def(def);
861                 for field in fields {
862                     let use_ctxt = field.node.ident.span;
863                     let index = self.tcx.field_index(field.node.id, self.tables);
864                     self.check_field(use_ctxt, field.span, adt, &variant.fields[index]);
865                 }
866             }
867             _ => {}
868         }
869
870         intravisit::walk_pat(self, pat);
871     }
872 }
873
874 ////////////////////////////////////////////////////////////////////////////////////////////
875 /// Type privacy visitor, checks types for privacy and reports violations.
876 /// Both explicitly written types and inferred types of expressions and patters are checked.
877 /// Checks are performed on "semantic" types regardless of names and their hygiene.
878 ////////////////////////////////////////////////////////////////////////////////////////////
879
880 struct TypePrivacyVisitor<'a, 'tcx: 'a> {
881     tcx: TyCtxt<'a, 'tcx, 'tcx>,
882     tables: &'a ty::TypeckTables<'tcx>,
883     current_item: DefId,
884     in_body: bool,
885     span: Span,
886     empty_tables: &'a ty::TypeckTables<'tcx>,
887 }
888
889 impl<'a, 'tcx> TypePrivacyVisitor<'a, 'tcx> {
890     fn item_is_accessible(&self, did: DefId) -> bool {
891         def_id_visibility(self.tcx, did).0.is_accessible_from(self.current_item, self.tcx)
892     }
893
894     // Take node-id of an expression or pattern and check its type for privacy.
895     fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
896         self.span = span;
897         if self.visit(self.tables.node_id_to_type(id)) || self.visit(self.tables.node_substs(id)) {
898             return true;
899         }
900         if let Some(adjustments) = self.tables.adjustments().get(id) {
901             for adjustment in adjustments {
902                 if self.visit(adjustment.target) {
903                     return true;
904                 }
905             }
906         }
907         false
908     }
909
910     fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
911         let is_error = !self.item_is_accessible(def_id);
912         if is_error {
913             self.tcx.sess.span_err(self.span, &format!("{} `{}` is private", kind, descr));
914         }
915         is_error
916     }
917 }
918
919 impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> {
920     /// We want to visit items in the context of their containing
921     /// module and so forth, so supply a crate for doing a deep walk.
922     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
923         NestedVisitorMap::All(&self.tcx.hir())
924     }
925
926     fn visit_mod(&mut self, _m: &'tcx hir::Mod, _s: Span, _n: ast::NodeId) {
927         // Don't visit nested modules, since we run a separate visitor walk
928         // for each module in `privacy_access_levels`
929     }
930
931     fn visit_nested_body(&mut self, body: hir::BodyId) {
932         let orig_tables = mem::replace(&mut self.tables, self.tcx.body_tables(body));
933         let orig_in_body = mem::replace(&mut self.in_body, true);
934         let body = self.tcx.hir().body(body);
935         self.visit_body(body);
936         self.tables = orig_tables;
937         self.in_body = orig_in_body;
938     }
939
940     fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty) {
941         self.span = hir_ty.span;
942         if self.in_body {
943             // Types in bodies.
944             if self.visit(self.tables.node_id_to_type(hir_ty.hir_id)) {
945                 return;
946             }
947         } else {
948             // Types in signatures.
949             // FIXME: This is very ineffective. Ideally each HIR type should be converted
950             // into a semantic type only once and the result should be cached somehow.
951             if self.visit(rustc_typeck::hir_ty_to_ty(self.tcx, hir_ty)) {
952                 return;
953             }
954         }
955
956         intravisit::walk_ty(self, hir_ty);
957     }
958
959     fn visit_trait_ref(&mut self, trait_ref: &'tcx hir::TraitRef) {
960         self.span = trait_ref.path.span;
961         if !self.in_body {
962             // Avoid calling `hir_trait_to_predicates` in bodies, it will ICE.
963             // The traits' privacy in bodies is already checked as a part of trait object types.
964             let (principal, projections) =
965                 rustc_typeck::hir_trait_to_predicates(self.tcx, trait_ref);
966             if self.visit_trait(*principal.skip_binder()) {
967                 return;
968             }
969             for (poly_predicate, _) in projections {
970                 let tcx = self.tcx;
971                 if self.visit(poly_predicate.skip_binder().ty) ||
972                    self.visit_trait(poly_predicate.skip_binder().projection_ty.trait_ref(tcx)) {
973                     return;
974                 }
975             }
976         }
977
978         intravisit::walk_trait_ref(self, trait_ref);
979     }
980
981     // Check types of expressions
982     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
983         if self.check_expr_pat_type(expr.hir_id, expr.span) {
984             // Do not check nested expressions if the error already happened.
985             return;
986         }
987         match expr.node {
988             hir::ExprKind::Assign(.., ref rhs) | hir::ExprKind::Match(ref rhs, ..) => {
989                 // Do not report duplicate errors for `x = y` and `match x { ... }`.
990                 if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
991                     return;
992                 }
993             }
994             hir::ExprKind::MethodCall(_, span, _) => {
995                 // Method calls have to be checked specially.
996                 self.span = span;
997                 if let Some(def) = self.tables.type_dependent_defs().get(expr.hir_id) {
998                     if self.visit(self.tcx.type_of(def.def_id())) {
999                         return;
1000                     }
1001                 } else {
1002                     self.tcx.sess.delay_span_bug(expr.span,
1003                                                  "no type-dependent def for method call");
1004                 }
1005             }
1006             _ => {}
1007         }
1008
1009         intravisit::walk_expr(self, expr);
1010     }
1011
1012     // Prohibit access to associated items with insufficient nominal visibility.
1013     //
1014     // Additionally, until better reachability analysis for macros 2.0 is available,
1015     // we prohibit access to private statics from other crates, this allows to give
1016     // more code internal visibility at link time. (Access to private functions
1017     // is already prohibited by type privacy for function types.)
1018     fn visit_qpath(&mut self, qpath: &'tcx hir::QPath, id: hir::HirId, span: Span) {
1019         let def = match *qpath {
1020             hir::QPath::Resolved(_, ref path) => match path.def {
1021                 Def::Method(..) | Def::AssociatedConst(..) |
1022                 Def::AssociatedTy(..) | Def::AssociatedExistential(..) |
1023                 Def::Static(..) => Some(path.def),
1024                 _ => None,
1025             }
1026             hir::QPath::TypeRelative(..) => {
1027                 self.tables.type_dependent_defs().get(id).cloned()
1028             }
1029         };
1030         if let Some(def) = def {
1031             let def_id = def.def_id();
1032             let is_local_static = if let Def::Static(..) = def { def_id.is_local() } else { false };
1033             if !self.item_is_accessible(def_id) && !is_local_static {
1034                 let name = match *qpath {
1035                     hir::QPath::Resolved(_, ref path) => path.to_string(),
1036                     hir::QPath::TypeRelative(_, ref segment) => segment.ident.to_string(),
1037                 };
1038                 let msg = format!("{} `{}` is private", def.kind_name(), name);
1039                 self.tcx.sess.span_err(span, &msg);
1040                 return;
1041             }
1042         }
1043
1044         intravisit::walk_qpath(self, qpath, id, span);
1045     }
1046
1047     // Check types of patterns.
1048     fn visit_pat(&mut self, pattern: &'tcx hir::Pat) {
1049         if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
1050             // Do not check nested patterns if the error already happened.
1051             return;
1052         }
1053
1054         intravisit::walk_pat(self, pattern);
1055     }
1056
1057     fn visit_local(&mut self, local: &'tcx hir::Local) {
1058         if let Some(ref init) = local.init {
1059             if self.check_expr_pat_type(init.hir_id, init.span) {
1060                 // Do not report duplicate errors for `let x = y`.
1061                 return;
1062             }
1063         }
1064
1065         intravisit::walk_local(self, local);
1066     }
1067
1068     // Check types in item interfaces.
1069     fn visit_item(&mut self, item: &'tcx hir::Item) {
1070         let orig_current_item =
1071             mem::replace(&mut self.current_item, self.tcx.hir().local_def_id(item.id));
1072         let orig_in_body = mem::replace(&mut self.in_body, false);
1073         let orig_tables =
1074             mem::replace(&mut self.tables, item_tables(self.tcx, item.id, self.empty_tables));
1075         intravisit::walk_item(self, item);
1076         self.tables = orig_tables;
1077         self.in_body = orig_in_body;
1078         self.current_item = orig_current_item;
1079     }
1080
1081     fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem) {
1082         let orig_tables =
1083             mem::replace(&mut self.tables, item_tables(self.tcx, ti.id, self.empty_tables));
1084         intravisit::walk_trait_item(self, ti);
1085         self.tables = orig_tables;
1086     }
1087
1088     fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem) {
1089         let orig_tables =
1090             mem::replace(&mut self.tables, item_tables(self.tcx, ii.id, self.empty_tables));
1091         intravisit::walk_impl_item(self, ii);
1092         self.tables = orig_tables;
1093     }
1094 }
1095
1096 impl<'a, 'tcx> DefIdVisitor<'a, 'tcx> for TypePrivacyVisitor<'a, 'tcx> {
1097     fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
1098     fn visit_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1099         self.check_def_id(def_id, kind, descr)
1100     }
1101 }
1102
1103 ///////////////////////////////////////////////////////////////////////////////
1104 /// Obsolete visitors for checking for private items in public interfaces.
1105 /// These visitors are supposed to be kept in frozen state and produce an
1106 /// "old error node set". For backward compatibility the new visitor reports
1107 /// warnings instead of hard errors when the erroneous node is not in this old set.
1108 ///////////////////////////////////////////////////////////////////////////////
1109
1110 struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx: 'a> {
1111     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1112     access_levels: &'a AccessLevels,
1113     in_variant: bool,
1114     // Set of errors produced by this obsolete visitor.
1115     old_error_set: NodeSet,
1116 }
1117
1118 struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> {
1119     inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>,
1120     /// Whether the type refers to private types.
1121     contains_private: bool,
1122     /// Whether we've recurred at all (i.e., if we're pointing at the
1123     /// first type on which `visit_ty` was called).
1124     at_outer_type: bool,
1125     /// Whether that first type is a public path.
1126     outer_type_is_public_path: bool,
1127 }
1128
1129 impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1130     fn path_is_private_type(&self, path: &hir::Path) -> bool {
1131         let did = match path.def {
1132             Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => return false,
1133             def => def.def_id(),
1134         };
1135
1136         // A path can only be private if:
1137         // it's in this crate...
1138         if let Some(node_id) = self.tcx.hir().as_local_node_id(did) {
1139             // .. and it corresponds to a private type in the AST (this returns
1140             // `None` for type parameters).
1141             match self.tcx.hir().find(node_id) {
1142                 Some(Node::Item(ref item)) => !item.vis.node.is_pub(),
1143                 Some(_) | None => false,
1144             }
1145         } else {
1146             return false
1147         }
1148     }
1149
1150     fn trait_is_public(&self, trait_id: ast::NodeId) -> bool {
1151         // FIXME: this would preferably be using `exported_items`, but all
1152         // traits are exported currently (see `EmbargoVisitor.exported_trait`).
1153         self.access_levels.is_public(trait_id)
1154     }
1155
1156     fn check_generic_bound(&mut self, bound: &hir::GenericBound) {
1157         if let hir::GenericBound::Trait(ref trait_ref, _) = *bound {
1158             if self.path_is_private_type(&trait_ref.trait_ref.path) {
1159                 self.old_error_set.insert(trait_ref.trait_ref.ref_id);
1160             }
1161         }
1162     }
1163
1164     fn item_is_public(&self, id: &ast::NodeId, vis: &hir::Visibility) -> bool {
1165         self.access_levels.is_reachable(*id) || vis.node.is_pub()
1166     }
1167 }
1168
1169 impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> {
1170     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'v> {
1171         NestedVisitorMap::None
1172     }
1173
1174     fn visit_ty(&mut self, ty: &hir::Ty) {
1175         if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = ty.node {
1176             if self.inner.path_is_private_type(path) {
1177                 self.contains_private = true;
1178                 // Found what we're looking for, so let's stop working.
1179                 return
1180             }
1181         }
1182         if let hir::TyKind::Path(_) = ty.node {
1183             if self.at_outer_type {
1184                 self.outer_type_is_public_path = true;
1185             }
1186         }
1187         self.at_outer_type = false;
1188         intravisit::walk_ty(self, ty)
1189     }
1190
1191     // Don't want to recurse into `[, .. expr]`.
1192     fn visit_expr(&mut self, _: &hir::Expr) {}
1193 }
1194
1195 impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
1196     /// We want to visit items in the context of their containing
1197     /// module and so forth, so supply a crate for doing a deep walk.
1198     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1199         NestedVisitorMap::All(&self.tcx.hir())
1200     }
1201
1202     fn visit_item(&mut self, item: &'tcx hir::Item) {
1203         match item.node {
1204             // Contents of a private mod can be re-exported, so we need
1205             // to check internals.
1206             hir::ItemKind::Mod(_) => {}
1207
1208             // An `extern {}` doesn't introduce a new privacy
1209             // namespace (the contents have their own privacies).
1210             hir::ItemKind::ForeignMod(_) => {}
1211
1212             hir::ItemKind::Trait(.., ref bounds, _) => {
1213                 if !self.trait_is_public(item.id) {
1214                     return
1215                 }
1216
1217                 for bound in bounds.iter() {
1218                     self.check_generic_bound(bound)
1219                 }
1220             }
1221
1222             // Impls need some special handling to try to offer useful
1223             // error messages without (too many) false positives
1224             // (i.e., we could just return here to not check them at
1225             // all, or some worse estimation of whether an impl is
1226             // publicly visible).
1227             hir::ItemKind::Impl(.., ref g, ref trait_ref, ref self_, ref impl_item_refs) => {
1228                 // `impl [... for] Private` is never visible.
1229                 let self_contains_private;
1230                 // `impl [... for] Public<...>`, but not `impl [... for]
1231                 // Vec<Public>` or `(Public,)`, etc.
1232                 let self_is_public_path;
1233
1234                 // Check the properties of the `Self` type:
1235                 {
1236                     let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor {
1237                         inner: self,
1238                         contains_private: false,
1239                         at_outer_type: true,
1240                         outer_type_is_public_path: false,
1241                     };
1242                     visitor.visit_ty(&self_);
1243                     self_contains_private = visitor.contains_private;
1244                     self_is_public_path = visitor.outer_type_is_public_path;
1245                 }
1246
1247                 // Miscellaneous info about the impl:
1248
1249                 // `true` iff this is `impl Private for ...`.
1250                 let not_private_trait =
1251                     trait_ref.as_ref().map_or(true, // no trait counts as public trait
1252                                               |tr| {
1253                         let did = tr.path.def.def_id();
1254
1255                         if let Some(node_id) = self.tcx.hir().as_local_node_id(did) {
1256                             self.trait_is_public(node_id)
1257                         } else {
1258                             true // external traits must be public
1259                         }
1260                     });
1261
1262                 // `true` iff this is a trait impl or at least one method is public.
1263                 //
1264                 // `impl Public { $( fn ...() {} )* }` is not visible.
1265                 //
1266                 // This is required over just using the methods' privacy
1267                 // directly because we might have `impl<T: Foo<Private>> ...`,
1268                 // and we shouldn't warn about the generics if all the methods
1269                 // are private (because `T` won't be visible externally).
1270                 let trait_or_some_public_method =
1271                     trait_ref.is_some() ||
1272                     impl_item_refs.iter()
1273                                  .any(|impl_item_ref| {
1274                                      let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1275                                      match impl_item.node {
1276                                          hir::ImplItemKind::Const(..) |
1277                                          hir::ImplItemKind::Method(..) => {
1278                                              self.access_levels.is_reachable(impl_item.id)
1279                                          }
1280                                          hir::ImplItemKind::Existential(..) |
1281                                          hir::ImplItemKind::Type(_) => false,
1282                                      }
1283                                  });
1284
1285                 if !self_contains_private &&
1286                         not_private_trait &&
1287                         trait_or_some_public_method {
1288
1289                     intravisit::walk_generics(self, g);
1290
1291                     match *trait_ref {
1292                         None => {
1293                             for impl_item_ref in impl_item_refs {
1294                                 // This is where we choose whether to walk down
1295                                 // further into the impl to check its items. We
1296                                 // should only walk into public items so that we
1297                                 // don't erroneously report errors for private
1298                                 // types in private items.
1299                                 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1300                                 match impl_item.node {
1301                                     hir::ImplItemKind::Const(..) |
1302                                     hir::ImplItemKind::Method(..)
1303                                         if self.item_is_public(&impl_item.id, &impl_item.vis) =>
1304                                     {
1305                                         intravisit::walk_impl_item(self, impl_item)
1306                                     }
1307                                     hir::ImplItemKind::Type(..) => {
1308                                         intravisit::walk_impl_item(self, impl_item)
1309                                     }
1310                                     _ => {}
1311                                 }
1312                             }
1313                         }
1314                         Some(ref tr) => {
1315                             // Any private types in a trait impl fall into three
1316                             // categories.
1317                             // 1. mentioned in the trait definition
1318                             // 2. mentioned in the type params/generics
1319                             // 3. mentioned in the associated types of the impl
1320                             //
1321                             // Those in 1. can only occur if the trait is in
1322                             // this crate and will've been warned about on the
1323                             // trait definition (there's no need to warn twice
1324                             // so we don't check the methods).
1325                             //
1326                             // Those in 2. are warned via walk_generics and this
1327                             // call here.
1328                             intravisit::walk_path(self, &tr.path);
1329
1330                             // Those in 3. are warned with this call.
1331                             for impl_item_ref in impl_item_refs {
1332                                 let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1333                                 if let hir::ImplItemKind::Type(ref ty) = impl_item.node {
1334                                     self.visit_ty(ty);
1335                                 }
1336                             }
1337                         }
1338                     }
1339                 } else if trait_ref.is_none() && self_is_public_path {
1340                     // `impl Public<Private> { ... }`. Any public static
1341                     // methods will be visible as `Public::foo`.
1342                     let mut found_pub_static = false;
1343                     for impl_item_ref in impl_item_refs {
1344                         if self.item_is_public(&impl_item_ref.id.node_id, &impl_item_ref.vis) {
1345                             let impl_item = self.tcx.hir().impl_item(impl_item_ref.id);
1346                             match impl_item_ref.kind {
1347                                 AssociatedItemKind::Const => {
1348                                     found_pub_static = true;
1349                                     intravisit::walk_impl_item(self, impl_item);
1350                                 }
1351                                 AssociatedItemKind::Method { has_self: false } => {
1352                                     found_pub_static = true;
1353                                     intravisit::walk_impl_item(self, impl_item);
1354                                 }
1355                                 _ => {}
1356                             }
1357                         }
1358                     }
1359                     if found_pub_static {
1360                         intravisit::walk_generics(self, g)
1361                     }
1362                 }
1363                 return
1364             }
1365
1366             // `type ... = ...;` can contain private types, because
1367             // we're introducing a new name.
1368             hir::ItemKind::Ty(..) => return,
1369
1370             // Not at all public, so we don't care.
1371             _ if !self.item_is_public(&item.id, &item.vis) => {
1372                 return;
1373             }
1374
1375             _ => {}
1376         }
1377
1378         // We've carefully constructed it so that if we're here, then
1379         // any `visit_ty`'s will be called on things that are in
1380         // public signatures, i.e., things that we're interested in for
1381         // this visitor.
1382         intravisit::walk_item(self, item);
1383     }
1384
1385     fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1386         for param in &generics.params {
1387             for bound in &param.bounds {
1388                 self.check_generic_bound(bound);
1389             }
1390         }
1391         for predicate in &generics.where_clause.predicates {
1392             match predicate {
1393                 hir::WherePredicate::BoundPredicate(bound_pred) => {
1394                     for bound in bound_pred.bounds.iter() {
1395                         self.check_generic_bound(bound)
1396                     }
1397                 }
1398                 hir::WherePredicate::RegionPredicate(_) => {}
1399                 hir::WherePredicate::EqPredicate(eq_pred) => {
1400                     self.visit_ty(&eq_pred.rhs_ty);
1401                 }
1402             }
1403         }
1404     }
1405
1406     fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem) {
1407         if self.access_levels.is_reachable(item.id) {
1408             intravisit::walk_foreign_item(self, item)
1409         }
1410     }
1411
1412     fn visit_ty(&mut self, t: &'tcx hir::Ty) {
1413         if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = t.node {
1414             if self.path_is_private_type(path) {
1415                 self.old_error_set.insert(t.id);
1416             }
1417         }
1418         intravisit::walk_ty(self, t)
1419     }
1420
1421     fn visit_variant(&mut self,
1422                      v: &'tcx hir::Variant,
1423                      g: &'tcx hir::Generics,
1424                      item_id: ast::NodeId) {
1425         if self.access_levels.is_reachable(v.node.data.id()) {
1426             self.in_variant = true;
1427             intravisit::walk_variant(self, v, g, item_id);
1428             self.in_variant = false;
1429         }
1430     }
1431
1432     fn visit_struct_field(&mut self, s: &'tcx hir::StructField) {
1433         if s.vis.node.is_pub() || self.in_variant {
1434             intravisit::walk_struct_field(self, s);
1435         }
1436     }
1437
1438     // We don't need to introspect into these at all: an
1439     // expression/block context can't possibly contain exported things.
1440     // (Making them no-ops stops us from traversing the whole AST without
1441     // having to be super careful about our `walk_...` calls above.)
1442     fn visit_block(&mut self, _: &'tcx hir::Block) {}
1443     fn visit_expr(&mut self, _: &'tcx hir::Expr) {}
1444 }
1445
1446 ///////////////////////////////////////////////////////////////////////////////
1447 /// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1448 /// finds any private components in it.
1449 /// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1450 /// and traits in public interfaces.
1451 ///////////////////////////////////////////////////////////////////////////////
1452
1453 struct SearchInterfaceForPrivateItemsVisitor<'a, 'tcx: 'a> {
1454     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1455     item_id: ast::NodeId,
1456     item_def_id: DefId,
1457     span: Span,
1458     /// The visitor checks that each component type is at least this visible.
1459     required_visibility: ty::Visibility,
1460     has_pub_restricted: bool,
1461     has_old_errors: bool,
1462     in_assoc_ty: bool,
1463     private_crates: FxHashSet<CrateNum>
1464 }
1465
1466 impl<'a, 'tcx: 'a> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1467     fn generics(&mut self) -> &mut Self {
1468         for param in &self.tcx.generics_of(self.item_def_id).params {
1469             match param.kind {
1470                 GenericParamDefKind::Type { has_default, .. } => {
1471                     if has_default {
1472                         self.visit(self.tcx.type_of(param.def_id));
1473                     }
1474                 }
1475                 GenericParamDefKind::Lifetime => {}
1476             }
1477         }
1478         self
1479     }
1480
1481     fn predicates(&mut self) -> &mut Self {
1482         // N.B., we use `explicit_predicates_of` and not `predicates_of`
1483         // because we don't want to report privacy errors due to where
1484         // clauses that the compiler inferred. We only want to
1485         // consider the ones that the user wrote. This is important
1486         // for the inferred outlives rules; see
1487         // `src/test/ui/rfc-2093-infer-outlives/privacy.rs`.
1488         self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id));
1489         self
1490     }
1491
1492     fn ty(&mut self) -> &mut Self {
1493         self.visit(self.tcx.type_of(self.item_def_id));
1494         self
1495     }
1496
1497     fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1498         if self.leaks_private_dep(def_id) {
1499             self.tcx.lint_node(lint::builtin::EXPORTED_PRIVATE_DEPENDENCIES,
1500                                self.item_id,
1501                                self.span,
1502                                &format!("{} `{}` from private dependency '{}' in public \
1503                                          interface", kind, descr,
1504                                          self.tcx.crate_name(def_id.krate)));
1505
1506         }
1507
1508         let node_id = match self.tcx.hir().as_local_node_id(def_id) {
1509             Some(node_id) => node_id,
1510             None => return false,
1511         };
1512
1513         let (vis, vis_span, vis_descr) = def_id_visibility(self.tcx, def_id);
1514         if !vis.is_at_least(self.required_visibility, self.tcx) {
1515             let msg = format!("{} {} `{}` in public interface", vis_descr, kind, descr);
1516             if self.has_pub_restricted || self.has_old_errors || self.in_assoc_ty {
1517                 let mut err = if kind == "trait" {
1518                     struct_span_err!(self.tcx.sess, self.span, E0445, "{}", msg)
1519                 } else {
1520                     struct_span_err!(self.tcx.sess, self.span, E0446, "{}", msg)
1521                 };
1522                 err.span_label(self.span, format!("can't leak {} {}", vis_descr, kind));
1523                 err.span_label(vis_span, format!("`{}` declared as {}", descr, vis_descr));
1524                 err.emit();
1525             } else {
1526                 let err_code = if kind == "trait" { "E0445" } else { "E0446" };
1527                 self.tcx.lint_node(lint::builtin::PRIVATE_IN_PUBLIC, node_id, self.span,
1528                                    &format!("{} (error {})", msg, err_code));
1529             }
1530
1531         }
1532
1533         false
1534     }
1535
1536     /// An item is 'leaked' from a private dependency if all
1537     /// of the following are true:
1538     /// 1. It's contained within a public type
1539     /// 2. It comes from a private crate
1540     fn leaks_private_dep(&self, item_id: DefId) -> bool {
1541         let ret = self.required_visibility == ty::Visibility::Public &&
1542             self.private_crates.contains(&item_id.krate);
1543
1544         debug!("leaks_private_dep(item_id={:?})={}", item_id, ret);
1545         return ret;
1546     }
1547 }
1548
1549 impl<'a, 'tcx> DefIdVisitor<'a, 'tcx> for SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1550     fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
1551     fn visit_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1552         self.check_def_id(def_id, kind, descr)
1553     }
1554 }
1555
1556 struct PrivateItemsInPublicInterfacesVisitor<'a, 'tcx: 'a> {
1557     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1558     has_pub_restricted: bool,
1559     old_error_set: &'a NodeSet,
1560     private_crates: FxHashSet<CrateNum>
1561 }
1562
1563 impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1564     fn check(&self, item_id: ast::NodeId, required_visibility: ty::Visibility)
1565              -> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> {
1566         let mut has_old_errors = false;
1567
1568         // Slow path taken only if there any errors in the crate.
1569         for &id in self.old_error_set {
1570             // Walk up the nodes until we find `item_id` (or we hit a root).
1571             let mut id = id;
1572             loop {
1573                 if id == item_id {
1574                     has_old_errors = true;
1575                     break;
1576                 }
1577                 let parent = self.tcx.hir().get_parent_node(id);
1578                 if parent == id {
1579                     break;
1580                 }
1581                 id = parent;
1582             }
1583
1584             if has_old_errors {
1585                 break;
1586             }
1587         }
1588
1589         SearchInterfaceForPrivateItemsVisitor {
1590             tcx: self.tcx,
1591             item_id,
1592             item_def_id: self.tcx.hir().local_def_id(item_id),
1593             span: self.tcx.hir().span(item_id),
1594             required_visibility,
1595             has_pub_restricted: self.has_pub_restricted,
1596             has_old_errors,
1597             in_assoc_ty: false,
1598             private_crates: self.private_crates.clone()
1599         }
1600     }
1601
1602     fn check_trait_or_impl_item(&self, node_id: ast::NodeId, assoc_item_kind: AssociatedItemKind,
1603                                 defaultness: hir::Defaultness, vis: ty::Visibility) {
1604         let mut check = self.check(node_id, vis);
1605
1606         let (check_ty, is_assoc_ty) = match assoc_item_kind {
1607             AssociatedItemKind::Const | AssociatedItemKind::Method { .. } => (true, false),
1608             AssociatedItemKind::Type => (defaultness.has_value(), true),
1609             // `ty()` for existential types is the underlying type,
1610             // it's not a part of interface, so we skip it.
1611             AssociatedItemKind::Existential => (false, true),
1612         };
1613         check.in_assoc_ty = is_assoc_ty;
1614         check.generics().predicates();
1615         if check_ty {
1616             check.ty();
1617         }
1618     }
1619 }
1620
1621 impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> {
1622     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1623         NestedVisitorMap::OnlyBodies(&self.tcx.hir())
1624     }
1625
1626     fn visit_item(&mut self, item: &'tcx hir::Item) {
1627         let tcx = self.tcx;
1628         let item_visibility = ty::Visibility::from_hir(&item.vis, item.id, tcx);
1629
1630         match item.node {
1631             // Crates are always public.
1632             hir::ItemKind::ExternCrate(..) => {}
1633             // All nested items are checked by `visit_item`.
1634             hir::ItemKind::Mod(..) => {}
1635             // Checked in resolve.
1636             hir::ItemKind::Use(..) => {}
1637             // No subitems.
1638             hir::ItemKind::GlobalAsm(..) => {}
1639             // Subitems of these items have inherited publicity.
1640             hir::ItemKind::Const(..) | hir::ItemKind::Static(..) |
1641             hir::ItemKind::Fn(..) | hir::ItemKind::Ty(..) => {
1642                 self.check(item.id, item_visibility).generics().predicates().ty();
1643             }
1644             hir::ItemKind::Existential(..) => {
1645                 // `ty()` for existential types is the underlying type,
1646                 // it's not a part of interface, so we skip it.
1647                 self.check(item.id, item_visibility).generics().predicates();
1648             }
1649             hir::ItemKind::Trait(.., ref trait_item_refs) => {
1650                 self.check(item.id, item_visibility).generics().predicates();
1651
1652                 for trait_item_ref in trait_item_refs {
1653                     self.check_trait_or_impl_item(trait_item_ref.id.node_id, trait_item_ref.kind,
1654                                                   trait_item_ref.defaultness, item_visibility);
1655                 }
1656             }
1657             hir::ItemKind::TraitAlias(..) => {
1658                 self.check(item.id, item_visibility).generics().predicates();
1659             }
1660             hir::ItemKind::Enum(ref def, _) => {
1661                 self.check(item.id, item_visibility).generics().predicates();
1662
1663                 for variant in &def.variants {
1664                     for field in variant.node.data.fields() {
1665                         self.check(field.id, item_visibility).ty();
1666                     }
1667                 }
1668             }
1669             // Subitems of foreign modules have their own publicity.
1670             hir::ItemKind::ForeignMod(ref foreign_mod) => {
1671                 for foreign_item in &foreign_mod.items {
1672                     let vis = ty::Visibility::from_hir(&foreign_item.vis, item.id, tcx);
1673                     self.check(foreign_item.id, vis).generics().predicates().ty();
1674                 }
1675             }
1676             // Subitems of structs and unions have their own publicity.
1677             hir::ItemKind::Struct(ref struct_def, _) |
1678             hir::ItemKind::Union(ref struct_def, _) => {
1679                 self.check(item.id, item_visibility).generics().predicates();
1680
1681                 for field in struct_def.fields() {
1682                     let field_visibility = ty::Visibility::from_hir(&field.vis, item.id, tcx);
1683                     self.check(field.id, min(item_visibility, field_visibility, tcx)).ty();
1684                 }
1685             }
1686             // An inherent impl is public when its type is public
1687             // Subitems of inherent impls have their own publicity.
1688             // A trait impl is public when both its type and its trait are public
1689             // Subitems of trait impls have inherited publicity.
1690             hir::ItemKind::Impl(.., ref trait_ref, _, ref impl_item_refs) => {
1691                 let impl_vis = ty::Visibility::of_impl(item.id, tcx, &Default::default());
1692                 self.check(item.id, impl_vis).generics().predicates();
1693                 for impl_item_ref in impl_item_refs {
1694                     let impl_item = tcx.hir().impl_item(impl_item_ref.id);
1695                     let impl_item_vis = if trait_ref.is_none() {
1696                         min(ty::Visibility::from_hir(&impl_item.vis, item.id, tcx), impl_vis, tcx)
1697                     } else {
1698                         impl_vis
1699                     };
1700                     self.check_trait_or_impl_item(impl_item_ref.id.node_id, impl_item_ref.kind,
1701                                                   impl_item_ref.defaultness, impl_item_vis);
1702                 }
1703             }
1704         }
1705     }
1706 }
1707
1708 pub fn provide(providers: &mut Providers) {
1709     *providers = Providers {
1710         privacy_access_levels,
1711         check_mod_privacy,
1712         ..*providers
1713     };
1714 }
1715
1716 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Lrc<AccessLevels> {
1717     tcx.privacy_access_levels(LOCAL_CRATE)
1718 }
1719
1720 fn check_mod_privacy<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>, module_def_id: DefId) {
1721     let empty_tables = ty::TypeckTables::empty(None);
1722
1723
1724     // Check privacy of names not checked in previous compilation stages.
1725     let mut visitor = NamePrivacyVisitor {
1726         tcx,
1727         tables: &empty_tables,
1728         current_item: DUMMY_NODE_ID,
1729         empty_tables: &empty_tables,
1730     };
1731     let (module, span, node_id) = tcx.hir().get_module(module_def_id);
1732     intravisit::walk_mod(&mut visitor, module, node_id);
1733
1734     // Check privacy of explicitly written types and traits as well as
1735     // inferred types of expressions and patterns.
1736     let mut visitor = TypePrivacyVisitor {
1737         tcx,
1738         tables: &empty_tables,
1739         current_item: module_def_id,
1740         in_body: false,
1741         span,
1742         empty_tables: &empty_tables,
1743     };
1744     intravisit::walk_mod(&mut visitor, module, node_id);
1745 }
1746
1747 fn privacy_access_levels<'tcx>(
1748     tcx: TyCtxt<'_, 'tcx, 'tcx>,
1749     krate: CrateNum,
1750 ) -> Lrc<AccessLevels> {
1751     assert_eq!(krate, LOCAL_CRATE);
1752
1753     let krate = tcx.hir().krate();
1754
1755     for &module in krate.modules.keys() {
1756         tcx.ensure().check_mod_privacy(tcx.hir().local_def_id(module));
1757     }
1758
1759     let private_crates: FxHashSet<CrateNum> = tcx.sess.opts.extern_private.iter()
1760         .flat_map(|c| {
1761             tcx.crates().iter().find(|&&krate| &tcx.crate_name(krate) == c).cloned()
1762         }).collect();
1763
1764
1765     // Build up a set of all exported items in the AST. This is a set of all
1766     // items which are reachable from external crates based on visibility.
1767     let mut visitor = EmbargoVisitor {
1768         tcx,
1769         access_levels: Default::default(),
1770         prev_level: Some(AccessLevel::Public),
1771         changed: false,
1772     };
1773     loop {
1774         intravisit::walk_crate(&mut visitor, krate);
1775         if visitor.changed {
1776             visitor.changed = false;
1777         } else {
1778             break
1779         }
1780     }
1781     visitor.update(ast::CRATE_NODE_ID, Some(AccessLevel::Public));
1782
1783     {
1784         let mut visitor = ObsoleteVisiblePrivateTypesVisitor {
1785             tcx,
1786             access_levels: &visitor.access_levels,
1787             in_variant: false,
1788             old_error_set: Default::default(),
1789         };
1790         intravisit::walk_crate(&mut visitor, krate);
1791
1792
1793         let has_pub_restricted = {
1794             let mut pub_restricted_visitor = PubRestrictedVisitor {
1795                 tcx,
1796                 has_pub_restricted: false
1797             };
1798             intravisit::walk_crate(&mut pub_restricted_visitor, krate);
1799             pub_restricted_visitor.has_pub_restricted
1800         };
1801
1802         // Check for private types and traits in public interfaces.
1803         let mut visitor = PrivateItemsInPublicInterfacesVisitor {
1804             tcx,
1805             has_pub_restricted,
1806             old_error_set: &visitor.old_error_set,
1807             private_crates
1808         };
1809         krate.visit_all_item_likes(&mut DeepVisitor::new(&mut visitor));
1810     }
1811
1812     Lrc::new(visitor.access_levels)
1813 }
1814
1815 __build_diagnostic_array! { librustc_privacy, DIAGNOSTICS }