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