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