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