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