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