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