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