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