Skip to main content

rustc_privacy/
lib.rs

1// tidy-alphabetical-start
2#![feature(associated_type_defaults)]
3#![feature(default_field_values)]
4#![feature(try_blocks)]
5// tidy-alphabetical-end
6
7mod errors;
8
9use std::fmt;
10use std::marker::PhantomData;
11use std::ops::ControlFlow;
12
13use errors::{
14    FieldIsPrivate, FieldIsPrivateLabel, FromPrivateDependencyInPublicInterface, InPublicInterface,
15    ItemIsPrivate, PrivateInterfacesOrBoundsLint, ReportEffectiveVisibility, UnnameableTypesLint,
16    UnnamedItemIsPrivate,
17};
18use rustc_ast::MacroDef;
19use rustc_ast::visit::{VisitorResult, try_visit};
20use rustc_data_structures::fx::FxHashSet;
21use rustc_data_structures::intern::Interned;
22use rustc_errors::{MultiSpan, listify};
23use rustc_hir as hir;
24use rustc_hir::def::{DefKind, Res};
25use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId};
26use rustc_hir::intravisit::{self, InferKind, Visitor};
27use rustc_hir::{AmbigArg, ForeignItemId, ItemId, OwnerId, PatKind, find_attr};
28use rustc_middle::middle::privacy::{EffectiveVisibilities, EffectiveVisibility, Level};
29use rustc_middle::query::Providers;
30use rustc_middle::ty::print::PrintTraitRefExt as _;
31use rustc_middle::ty::{
32    self, AssocContainer, Const, GenericParamDefKind, TraitRef, Ty, TyCtxt, TypeSuperVisitable,
33    TypeVisitable, TypeVisitor,
34};
35use rustc_middle::{bug, span_bug};
36use rustc_session::lint;
37use rustc_span::hygiene::Transparency;
38use rustc_span::{Ident, Span, Symbol, sym};
39use tracing::debug;
40
41////////////////////////////////////////////////////////////////////////////////
42// Generic infrastructure used to implement specific visitors below.
43////////////////////////////////////////////////////////////////////////////////
44
45struct LazyDefPathStr<'tcx> {
46    def_id: DefId,
47    tcx: TyCtxt<'tcx>,
48}
49
50impl<'tcx> fmt::Display for LazyDefPathStr<'tcx> {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        f.write_fmt(format_args!("{0}", self.tcx.def_path_str(self.def_id)))write!(f, "{}", self.tcx.def_path_str(self.def_id))
53    }
54}
55
56/// Implemented to visit all `DefId`s in a type.
57/// Visiting `DefId`s is useful because visibilities and reachabilities are attached to them.
58/// The idea is to visit "all components of a type", as documented in
59/// <https://github.com/rust-lang/rfcs/blob/master/text/2145-type-privacy.md#how-to-determine-visibility-of-a-type>.
60/// The default type visitor (`TypeVisitor`) does most of the job, but it has some shortcomings.
61/// First, it doesn't have overridable `fn visit_trait_ref`, so we have to catch trait `DefId`s
62/// manually. Second, it doesn't visit some type components like signatures of fn types, or traits
63/// in `impl Trait`, see individual comments in `DefIdVisitorSkeleton::visit_ty`.
64pub trait DefIdVisitor<'tcx> {
65    type Result: VisitorResult = ();
66    const SHALLOW: bool = false;
67    fn skip_assoc_tys(&self) -> bool {
68        false
69    }
70
71    fn tcx(&self) -> TyCtxt<'tcx>;
72    /// NOTE: Def-id visiting should be idempotent (or at least produce duplicated errors),
73    /// because `DefIdVisitorSkeleton` will use caching and sometimes avoid visiting duplicate
74    /// def-ids. All the current visitors follow this rule.
75    fn visit_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display)
76    -> Self::Result;
77
78    /// Not overridden, but used to actually visit types and traits.
79    fn skeleton(&mut self) -> DefIdVisitorSkeleton<'_, 'tcx, Self> {
80        DefIdVisitorSkeleton {
81            def_id_visitor: self,
82            visited_tys: Default::default(),
83            dummy: Default::default(),
84        }
85    }
86    fn visit(&mut self, ty_fragment: impl TypeVisitable<TyCtxt<'tcx>>) -> Self::Result {
87        ty_fragment.visit_with(&mut self.skeleton())
88    }
89    fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> Self::Result {
90        self.skeleton().visit_trait(trait_ref)
91    }
92    fn visit_predicates(&mut self, predicates: ty::GenericPredicates<'tcx>) -> Self::Result {
93        self.skeleton().visit_clauses(predicates.predicates)
94    }
95    fn visit_clauses(&mut self, clauses: &[(ty::Clause<'tcx>, Span)]) -> Self::Result {
96        self.skeleton().visit_clauses(clauses)
97    }
98}
99
100pub struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> {
101    def_id_visitor: &'v mut V,
102    visited_tys: FxHashSet<Ty<'tcx>>,
103    dummy: PhantomData<TyCtxt<'tcx>>,
104}
105
106impl<'tcx, V> DefIdVisitorSkeleton<'_, 'tcx, V>
107where
108    V: DefIdVisitor<'tcx> + ?Sized,
109{
110    fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> V::Result {
111        let TraitRef { def_id, args, .. } = trait_ref;
112        match ::rustc_ast_ir::visit::VisitorResult::branch(self.def_id_visitor.visit_def_id(def_id,
            "trait", &trait_ref.print_only_trait_path())) {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(self.def_id_visitor.visit_def_id(
113            def_id,
114            "trait",
115            &trait_ref.print_only_trait_path()
116        ));
117        if V::SHALLOW { V::Result::output() } else { args.visit_with(self) }
118    }
119
120    fn visit_projection_term(&mut self, projection: ty::AliasTerm<'tcx>) -> V::Result {
121        let tcx = self.def_id_visitor.tcx();
122        let (trait_ref, assoc_args) = projection.trait_ref_and_own_args(tcx);
123        match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_trait(trait_ref))
    {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(self.visit_trait(trait_ref));
124        if V::SHALLOW {
125            V::Result::output()
126        } else {
127            V::Result::from_branch(
128                assoc_args.iter().try_for_each(|arg| arg.visit_with(self).branch()),
129            )
130        }
131    }
132
133    fn visit_clause(&mut self, clause: ty::Clause<'tcx>) -> V::Result {
134        match clause.kind().skip_binder() {
135            ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity: _ }) => {
136                self.visit_trait(trait_ref)
137            }
138            ty::ClauseKind::HostEffect(pred) => {
139                match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_trait(pred.trait_ref))
    {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(self.visit_trait(pred.trait_ref));
140                pred.constness.visit_with(self)
141            }
142            ty::ClauseKind::Projection(ty::ProjectionPredicate {
143                projection_term: projection_ty,
144                term,
145            }) => {
146                match ::rustc_ast_ir::visit::VisitorResult::branch(term.visit_with(self)) {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(term.visit_with(self));
147                self.visit_projection_term(projection_ty)
148            }
149            ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _region)) => ty.visit_with(self),
150            ty::ClauseKind::RegionOutlives(..) => V::Result::output(),
151            ty::ClauseKind::ConstArgHasType(ct, ty) => {
152                match ::rustc_ast_ir::visit::VisitorResult::branch(ct.visit_with(self)) {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(ct.visit_with(self));
153                ty.visit_with(self)
154            }
155            ty::ClauseKind::ConstEvaluatable(ct) => ct.visit_with(self),
156            ty::ClauseKind::WellFormed(term) => term.visit_with(self),
157            ty::ClauseKind::UnstableFeature(_) => V::Result::output(),
158        }
159    }
160
161    fn visit_clauses(&mut self, clauses: &[(ty::Clause<'tcx>, Span)]) -> V::Result {
162        for &(clause, _) in clauses {
163            match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_clause(clause))
    {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(self.visit_clause(clause));
164        }
165        V::Result::output()
166    }
167}
168
169impl<'tcx, V> TypeVisitor<TyCtxt<'tcx>> for DefIdVisitorSkeleton<'_, 'tcx, V>
170where
171    V: DefIdVisitor<'tcx> + ?Sized,
172{
173    type Result = V::Result;
174
175    fn visit_predicate(&mut self, p: ty::Predicate<'tcx>) -> Self::Result {
176        self.visit_clause(p.as_clause().unwrap())
177    }
178
179    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
180        let tcx = self.def_id_visitor.tcx();
181        // GenericArgs are not visited here because they are visited below
182        // in `super_visit_with`.
183        let ty_kind = *ty.kind();
184        match ty_kind {
185            ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), ..)
186            | ty::Foreign(def_id)
187            | ty::FnDef(def_id, ..)
188            | ty::Closure(def_id, ..)
189            | ty::CoroutineClosure(def_id, ..)
190            | ty::Coroutine(def_id, ..) => {
191                match ::rustc_ast_ir::visit::VisitorResult::branch(self.def_id_visitor.visit_def_id(def_id,
            "type", &ty)) {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(self.def_id_visitor.visit_def_id(def_id, "type", &ty));
192                if V::SHALLOW {
193                    return V::Result::output();
194                }
195                // Default type visitor doesn't visit signatures of fn types.
196                // Something like `fn() -> Priv {my_func}` is considered a private type even if
197                // `my_func` is public, so we need to visit signatures.
198                if let ty::FnDef(..) = ty_kind {
199                    // FIXME: this should probably use `args` from `FnDef`
200                    match ::rustc_ast_ir::visit::VisitorResult::branch(tcx.fn_sig(def_id).instantiate_identity().visit_with(self))
    {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(tcx.fn_sig(def_id).instantiate_identity().visit_with(self));
201                }
202                // Inherent static methods don't have self type in args.
203                // Something like `fn() {my_method}` type of the method
204                // `impl Pub<Priv> { pub fn my_method() {} }` is considered a private type,
205                // so we need to visit the self type additionally.
206                if let Some(assoc_item) = tcx.opt_associated_item(def_id)
207                    && let Some(impl_def_id) = assoc_item.impl_container(tcx)
208                {
209                    match ::rustc_ast_ir::visit::VisitorResult::branch(tcx.type_of(impl_def_id).instantiate_identity().visit_with(self))
    {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(tcx.type_of(impl_def_id).instantiate_identity().visit_with(self));
210                }
211            }
212            ty::Alias(kind @ (ty::Inherent | ty::Free | ty::Projection), data) => {
213                if self.def_id_visitor.skip_assoc_tys() {
214                    // Visitors searching for minimal visibility/reachability want to
215                    // conservatively approximate associated types like `Type::Alias`
216                    // as visible/reachable even if `Type` is private.
217                    // Ideally, associated types should be instantiated in the same way as
218                    // free type aliases, but this isn't done yet.
219                    return V::Result::output();
220                }
221                if !self.visited_tys.insert(ty) {
222                    // Avoid repeatedly visiting alias types (including projections).
223                    // This helps with special cases like #145741, but doesn't introduce
224                    // too much overhead in general case, unlike caching for other types.
225                    return V::Result::output();
226                }
227
228                match ::rustc_ast_ir::visit::VisitorResult::branch(self.def_id_visitor.visit_def_id(data.def_id,
            match kind {
                ty::Inherent | ty::Projection => "associated type",
                ty::Free => "type alias",
                ty::Opaque =>
                    ::core::panicking::panic("internal error: entered unreachable code"),
            }, &LazyDefPathStr { def_id: data.def_id, tcx })) {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(self.def_id_visitor.visit_def_id(
229                    data.def_id,
230                    match kind {
231                        ty::Inherent | ty::Projection => "associated type",
232                        ty::Free => "type alias",
233                        ty::Opaque => unreachable!(),
234                    },
235                    &LazyDefPathStr { def_id: data.def_id, tcx },
236                ));
237
238                // This will also visit args if necessary, so we don't need to recurse.
239                return if V::SHALLOW {
240                    V::Result::output()
241                } else if kind == ty::Projection {
242                    self.visit_projection_term(data.into())
243                } else {
244                    V::Result::from_branch(
245                        data.args.iter().try_for_each(|arg| arg.visit_with(self).branch()),
246                    )
247                };
248            }
249            ty::Dynamic(predicates, ..) => {
250                // All traits in the list are considered the "primary" part of the type
251                // and are visited by shallow visitors.
252                for predicate in predicates {
253                    let trait_ref = match predicate.skip_binder() {
254                        ty::ExistentialPredicate::Trait(trait_ref) => trait_ref,
255                        ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx),
256                        ty::ExistentialPredicate::AutoTrait(def_id) => {
257                            ty::ExistentialTraitRef::new(tcx, def_id, ty::GenericArgs::empty())
258                        }
259                    };
260                    let ty::ExistentialTraitRef { def_id, .. } = trait_ref;
261                    match ::rustc_ast_ir::visit::VisitorResult::branch(self.def_id_visitor.visit_def_id(def_id,
            "trait", &trait_ref)) {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref));
262                }
263            }
264            ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => {
265                // Skip repeated `Opaque`s to avoid infinite recursion.
266                if self.visited_tys.insert(ty) {
267                    // The intent is to treat `impl Trait1 + Trait2` identically to
268                    // `dyn Trait1 + Trait2`. Therefore we ignore def-id of the opaque type itself
269                    // (it either has no visibility, or its visibility is insignificant, like
270                    // visibilities of type aliases) and recurse into bounds instead to go
271                    // through the trait list (default type visitor doesn't visit those traits).
272                    // All traits in the list are considered the "primary" part of the type
273                    // and are visited by shallow visitors.
274                    match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_clauses(tcx.explicit_item_bounds(def_id).skip_binder()))
    {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(self.visit_clauses(tcx.explicit_item_bounds(def_id).skip_binder()));
275                }
276            }
277            // These types don't have their own def-ids (but may have subcomponents
278            // with def-ids that should be visited recursively).
279            ty::Bool
280            | ty::Char
281            | ty::Int(..)
282            | ty::Uint(..)
283            | ty::Float(..)
284            | ty::Str
285            | ty::Never
286            | ty::Array(..)
287            | ty::Slice(..)
288            | ty::Tuple(..)
289            | ty::RawPtr(..)
290            | ty::Ref(..)
291            | ty::Pat(..)
292            | ty::FnPtr(..)
293            | ty::UnsafeBinder(_)
294            | ty::Param(..)
295            | ty::Bound(..)
296            | ty::Error(_)
297            | ty::CoroutineWitness(..) => {}
298            ty::Placeholder(..) | ty::Infer(..) => {
299                ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected type: {0:?}", ty))bug!("unexpected type: {:?}", ty)
300            }
301        }
302
303        if V::SHALLOW { V::Result::output() } else { ty.super_visit_with(self) }
304    }
305
306    fn visit_const(&mut self, c: Const<'tcx>) -> Self::Result {
307        let tcx = self.def_id_visitor.tcx();
308        tcx.expand_abstract_consts(c).super_visit_with(self)
309    }
310}
311
312fn assoc_has_type_of(tcx: TyCtxt<'_>, item: &ty::AssocItem) -> bool {
313    if let ty::AssocKind::Type { data: ty::AssocTypeData::Normal(..) } = item.kind
314        && let hir::Node::TraitItem(item) =
315            tcx.hir_node(tcx.local_def_id_to_hir_id(item.def_id.expect_local()))
316        && let hir::TraitItemKind::Type(_, None) = item.kind
317    {
318        false
319    } else {
320        true
321    }
322}
323
324fn min(vis1: ty::Visibility, vis2: ty::Visibility, tcx: TyCtxt<'_>) -> ty::Visibility {
325    if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 }
326}
327
328/// Visitor used to determine impl visibility and reachability.
329struct FindMin<'a, 'tcx, VL: VisibilityLike, const SHALLOW: bool> {
330    tcx: TyCtxt<'tcx>,
331    effective_visibilities: &'a EffectiveVisibilities,
332    min: VL,
333}
334
335impl<'a, 'tcx, VL: VisibilityLike, const SHALLOW: bool> DefIdVisitor<'tcx>
336    for FindMin<'a, 'tcx, VL, SHALLOW>
337{
338    const SHALLOW: bool = SHALLOW;
339    fn skip_assoc_tys(&self) -> bool {
340        true
341    }
342    fn tcx(&self) -> TyCtxt<'tcx> {
343        self.tcx
344    }
345    fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) {
346        if let Some(def_id) = def_id.as_local() {
347            self.min = VL::new_min(self, def_id);
348        }
349    }
350}
351
352trait VisibilityLike: Sized {
353    const MAX: Self;
354    fn new_min<const SHALLOW: bool>(
355        find: &FindMin<'_, '_, Self, SHALLOW>,
356        def_id: LocalDefId,
357    ) -> Self;
358
359    // Returns an over-approximation (`skip_assoc_tys()` = true) of visibility due to
360    // associated types for which we can't determine visibility precisely.
361    fn of_impl<const SHALLOW: bool>(
362        def_id: LocalDefId,
363        of_trait: bool,
364        tcx: TyCtxt<'_>,
365        effective_visibilities: &EffectiveVisibilities,
366    ) -> Self {
367        let mut find = FindMin::<_, SHALLOW> { tcx, effective_visibilities, min: Self::MAX };
368        find.visit(tcx.type_of(def_id).instantiate_identity());
369        if of_trait {
370            find.visit_trait(tcx.impl_trait_ref(def_id).instantiate_identity());
371        }
372        find.min
373    }
374}
375
376impl VisibilityLike for ty::Visibility {
377    const MAX: Self = ty::Visibility::Public;
378    fn new_min<const SHALLOW: bool>(
379        find: &FindMin<'_, '_, Self, SHALLOW>,
380        def_id: LocalDefId,
381    ) -> Self {
382        min(find.tcx.local_visibility(def_id), find.min, find.tcx)
383    }
384}
385
386impl VisibilityLike for EffectiveVisibility {
387    const MAX: Self = EffectiveVisibility::from_vis(ty::Visibility::Public);
388    fn new_min<const SHALLOW: bool>(
389        find: &FindMin<'_, '_, Self, SHALLOW>,
390        def_id: LocalDefId,
391    ) -> Self {
392        let effective_vis =
393            find.effective_visibilities.effective_vis(def_id).copied().unwrap_or_else(|| {
394                let private_vis = ty::Visibility::Restricted(
395                    find.tcx.parent_module_from_def_id(def_id).to_local_def_id(),
396                );
397                EffectiveVisibility::from_vis(private_vis)
398            });
399
400        effective_vis.min(find.min, find.tcx)
401    }
402}
403
404/// The embargo visitor, used to determine the exports of the AST.
405struct EmbargoVisitor<'tcx> {
406    tcx: TyCtxt<'tcx>,
407
408    /// Effective visibilities for reachable nodes.
409    effective_visibilities: EffectiveVisibilities,
410    /// A set of pairs corresponding to modules, where the first module is
411    /// reachable via a macro that's defined in the second module. This cannot
412    /// be represented as reachable because it can't handle the following case:
413    ///
414    /// pub mod n {                         // Should be `Public`
415    ///     pub(crate) mod p {              // Should *not* be accessible
416    ///         pub fn f() -> i32 { 12 }    // Must be `Reachable`
417    ///     }
418    /// }
419    /// pub macro m() {
420    ///     n::p::f()
421    /// }
422    macro_reachable: FxHashSet<(LocalModDefId, LocalModDefId)>,
423    /// Has something changed in the level map?
424    changed: bool,
425}
426
427struct ReachEverythingInTheInterfaceVisitor<'a, 'tcx> {
428    effective_vis: EffectiveVisibility,
429    item_def_id: LocalDefId,
430    ev: &'a mut EmbargoVisitor<'tcx>,
431    level: Level,
432}
433
434impl<'tcx> EmbargoVisitor<'tcx> {
435    fn get(&self, def_id: LocalDefId) -> Option<EffectiveVisibility> {
436        self.effective_visibilities.effective_vis(def_id).copied()
437    }
438
439    // Updates node effective visibility.
440    fn update(
441        &mut self,
442        def_id: LocalDefId,
443        inherited_effective_vis: EffectiveVisibility,
444        level: Level,
445    ) {
446        let nominal_vis = self.tcx.local_visibility(def_id);
447        self.update_eff_vis(def_id, inherited_effective_vis, Some(nominal_vis), level);
448    }
449
450    fn update_eff_vis(
451        &mut self,
452        def_id: LocalDefId,
453        inherited_effective_vis: EffectiveVisibility,
454        max_vis: Option<ty::Visibility>,
455        level: Level,
456    ) {
457        // FIXME(typed_def_id): Make `Visibility::Restricted` use a `LocalModDefId` by default.
458        let private_vis =
459            ty::Visibility::Restricted(self.tcx.parent_module_from_def_id(def_id).into());
460        if max_vis != Some(private_vis) {
461            self.changed |= self.effective_visibilities.update(
462                def_id,
463                max_vis,
464                || private_vis,
465                inherited_effective_vis,
466                level,
467                self.tcx,
468            );
469        }
470    }
471
472    fn reach(
473        &mut self,
474        def_id: LocalDefId,
475        effective_vis: EffectiveVisibility,
476    ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
477        ReachEverythingInTheInterfaceVisitor {
478            effective_vis,
479            item_def_id: def_id,
480            ev: self,
481            level: Level::Reachable,
482        }
483    }
484
485    fn reach_through_impl_trait(
486        &mut self,
487        def_id: LocalDefId,
488        effective_vis: EffectiveVisibility,
489    ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
490        ReachEverythingInTheInterfaceVisitor {
491            effective_vis,
492            item_def_id: def_id,
493            ev: self,
494            level: Level::ReachableThroughImplTrait,
495        }
496    }
497
498    // We have to make sure that the items that macros might reference
499    // are reachable, since they might be exported transitively.
500    fn update_reachability_from_macro(
501        &mut self,
502        local_def_id: LocalDefId,
503        md: &MacroDef,
504        macro_ev: EffectiveVisibility,
505    ) {
506        // Non-opaque macros cannot make other items more accessible than they already are.
507        let hir_id = self.tcx.local_def_id_to_hir_id(local_def_id);
508        let attrs = self.tcx.hir_attrs(hir_id);
509
510        if {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(RustcMacroTransparency(x)) => {
                    break 'done Some(*x);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, RustcMacroTransparency(x) => *x)
511            .unwrap_or(Transparency::fallback(md.macro_rules))
512            != Transparency::Opaque
513        {
514            return;
515        }
516
517        let macro_module_def_id = self.tcx.local_parent(local_def_id);
518        if self.tcx.def_kind(macro_module_def_id) != DefKind::Mod {
519            // The macro's parent doesn't correspond to a `mod`, return early (#63164, #65252).
520            return;
521        }
522        // FIXME(typed_def_id): Introduce checked constructors that check def_kind.
523        let macro_module_def_id = LocalModDefId::new_unchecked(macro_module_def_id);
524
525        if self.effective_visibilities.public_at_level(local_def_id).is_none() {
526            return;
527        }
528
529        // Since we are starting from an externally visible module,
530        // all the parents in the loop below are also guaranteed to be modules.
531        let mut module_def_id = macro_module_def_id;
532        loop {
533            let changed_reachability =
534                self.update_macro_reachable(module_def_id, macro_module_def_id, macro_ev);
535            if changed_reachability || module_def_id == LocalModDefId::CRATE_DEF_ID {
536                break;
537            }
538            module_def_id = LocalModDefId::new_unchecked(self.tcx.local_parent(module_def_id));
539        }
540    }
541
542    /// Updates the item as being reachable through a macro defined in the given
543    /// module. Returns `true` if the level has changed.
544    fn update_macro_reachable(
545        &mut self,
546        module_def_id: LocalModDefId,
547        defining_mod: LocalModDefId,
548        macro_ev: EffectiveVisibility,
549    ) -> bool {
550        if self.macro_reachable.insert((module_def_id, defining_mod)) {
551            for child in self.tcx.module_children_local(module_def_id.to_local_def_id()) {
552                if let Res::Def(def_kind, def_id) = child.res
553                    && let Some(def_id) = def_id.as_local()
554                    && child.vis.is_accessible_from(defining_mod, self.tcx)
555                {
556                    let vis = self.tcx.local_visibility(def_id);
557                    self.update_macro_reachable_def(def_id, def_kind, vis, defining_mod, macro_ev);
558                }
559            }
560            true
561        } else {
562            false
563        }
564    }
565
566    fn update_macro_reachable_def(
567        &mut self,
568        def_id: LocalDefId,
569        def_kind: DefKind,
570        vis: ty::Visibility,
571        module: LocalModDefId,
572        macro_ev: EffectiveVisibility,
573    ) {
574        self.update(def_id, macro_ev, Level::Reachable);
575        match def_kind {
576            // No type privacy, so can be directly marked as reachable.
577            DefKind::Const { .. }
578            | DefKind::Static { .. }
579            | DefKind::TraitAlias
580            | DefKind::TyAlias => {
581                if vis.is_accessible_from(module, self.tcx) {
582                    self.update(def_id, macro_ev, Level::Reachable);
583                }
584            }
585
586            // Hygiene isn't really implemented for `macro_rules!` macros at the
587            // moment. Accordingly, marking them as reachable is unwise. `macro` macros
588            // have normal hygiene, so we can treat them like other items without type
589            // privacy and mark them reachable.
590            DefKind::Macro(_) => {
591                let item = self.tcx.hir_expect_item(def_id);
592                if let hir::ItemKind::Macro(_, MacroDef { macro_rules: false, .. }, _) = item.kind {
593                    if vis.is_accessible_from(module, self.tcx) {
594                        self.update(def_id, macro_ev, Level::Reachable);
595                    }
596                }
597            }
598
599            // We can't use a module name as the final segment of a path, except
600            // in use statements. Since re-export checking doesn't consider
601            // hygiene these don't need to be marked reachable. The contents of
602            // the module, however may be reachable.
603            DefKind::Mod => {
604                if vis.is_accessible_from(module, self.tcx) {
605                    self.update_macro_reachable(
606                        LocalModDefId::new_unchecked(def_id),
607                        module,
608                        macro_ev,
609                    );
610                }
611            }
612
613            DefKind::Struct | DefKind::Union => {
614                // While structs and unions have type privacy, their fields do not.
615                let struct_def = self.tcx.adt_def(def_id);
616                for field in &struct_def.non_enum_variant().fields {
617                    let def_id = field.did.expect_local();
618                    let field_vis = self.tcx.local_visibility(def_id);
619                    if field_vis.is_accessible_from(module, self.tcx) {
620                        self.reach(def_id, macro_ev).ty();
621                    }
622                }
623            }
624
625            // These have type privacy, so are not reachable unless they're
626            // public, or are not namespaced at all.
627            DefKind::AssocConst { .. }
628            | DefKind::AssocTy
629            | DefKind::ConstParam
630            | DefKind::Ctor(_, _)
631            | DefKind::Enum
632            | DefKind::ForeignTy
633            | DefKind::Fn
634            | DefKind::OpaqueTy
635            | DefKind::AssocFn
636            | DefKind::Trait
637            | DefKind::TyParam
638            | DefKind::Variant
639            | DefKind::LifetimeParam
640            | DefKind::ExternCrate
641            | DefKind::Use
642            | DefKind::ForeignMod
643            | DefKind::AnonConst
644            | DefKind::InlineConst
645            | DefKind::Field
646            | DefKind::GlobalAsm
647            | DefKind::Impl { .. }
648            | DefKind::Closure
649            | DefKind::SyntheticCoroutineBody => (),
650        }
651    }
652}
653
654impl<'tcx> EmbargoVisitor<'tcx> {
655    fn check_assoc_item(&mut self, item: &ty::AssocItem, item_ev: EffectiveVisibility) {
656        let def_id = item.def_id.expect_local();
657        let tcx = self.tcx;
658        let mut reach = self.reach(def_id, item_ev);
659        reach.generics().predicates();
660        if assoc_has_type_of(tcx, item) {
661            reach.ty();
662        }
663        if item.is_type() && item.container == AssocContainer::Trait {
664            reach.bounds();
665        }
666    }
667
668    fn check_def_id(&mut self, owner_id: OwnerId) {
669        // Update levels of nested things and mark all items
670        // in interfaces of reachable items as reachable.
671        let item_ev = self.get(owner_id.def_id);
672        match self.tcx.def_kind(owner_id) {
673            // The interface is empty, and no nested items.
674            DefKind::Use | DefKind::ExternCrate | DefKind::GlobalAsm => {}
675            // The interface is empty, and all nested items are processed by `check_def_id`.
676            DefKind::Mod => {}
677            DefKind::Macro { .. } => {
678                if let Some(item_ev) = item_ev {
679                    let (_, macro_def, _) =
680                        self.tcx.hir_expect_item(owner_id.def_id).expect_macro();
681                    self.update_reachability_from_macro(owner_id.def_id, macro_def, item_ev);
682                }
683            }
684            DefKind::ForeignTy
685            | DefKind::Const { .. }
686            | DefKind::Static { .. }
687            | DefKind::Fn
688            | DefKind::TyAlias => {
689                if let Some(item_ev) = item_ev {
690                    self.reach(owner_id.def_id, item_ev).generics().predicates().ty();
691                }
692            }
693            DefKind::Trait => {
694                if let Some(item_ev) = item_ev {
695                    self.reach(owner_id.def_id, item_ev).generics().predicates();
696
697                    for assoc_item in self.tcx.associated_items(owner_id).in_definition_order() {
698                        let def_id = assoc_item.def_id.expect_local();
699                        self.update(def_id, item_ev, Level::Reachable);
700
701                        self.check_assoc_item(assoc_item, item_ev);
702                    }
703                }
704            }
705            DefKind::TraitAlias => {
706                if let Some(item_ev) = item_ev {
707                    self.reach(owner_id.def_id, item_ev).generics().predicates();
708                }
709            }
710            DefKind::Impl { of_trait } => {
711                // Type inference is very smart sometimes. It can make an impl reachable even some
712                // components of its type or trait are unreachable. E.g. methods of
713                // `impl ReachableTrait<UnreachableTy> for ReachableTy<UnreachableTy> { ... }`
714                // can be usable from other crates (#57264). So we skip args when calculating
715                // reachability and consider an impl reachable if its "shallow" type and trait are
716                // reachable.
717                //
718                // The assumption we make here is that type-inference won't let you use an impl
719                // without knowing both "shallow" version of its self type and "shallow" version of
720                // its trait if it exists (which require reaching the `DefId`s in them).
721                let item_ev = EffectiveVisibility::of_impl::<true>(
722                    owner_id.def_id,
723                    of_trait,
724                    self.tcx,
725                    &self.effective_visibilities,
726                );
727
728                self.update_eff_vis(owner_id.def_id, item_ev, None, Level::Direct);
729
730                {
731                    let mut reach = self.reach(owner_id.def_id, item_ev);
732                    reach.generics().predicates().ty();
733                    if of_trait {
734                        reach.trait_ref();
735                    }
736                }
737
738                for assoc_item in self.tcx.associated_items(owner_id).in_definition_order() {
739                    let def_id = assoc_item.def_id.expect_local();
740                    let max_vis =
741                        if of_trait { None } else { Some(self.tcx.local_visibility(def_id)) };
742                    self.update_eff_vis(def_id, item_ev, max_vis, Level::Direct);
743
744                    if let Some(impl_item_ev) = self.get(def_id) {
745                        self.check_assoc_item(assoc_item, impl_item_ev);
746                    }
747                }
748            }
749            DefKind::Enum => {
750                if let Some(item_ev) = item_ev {
751                    self.reach(owner_id.def_id, item_ev).generics().predicates();
752                }
753                let def = self.tcx.adt_def(owner_id);
754                for variant in def.variants() {
755                    if let Some(item_ev) = item_ev {
756                        self.update(variant.def_id.expect_local(), item_ev, Level::Reachable);
757                    }
758
759                    if let Some(variant_ev) = self.get(variant.def_id.expect_local()) {
760                        if let Some(ctor_def_id) = variant.ctor_def_id() {
761                            self.update(ctor_def_id.expect_local(), variant_ev, Level::Reachable);
762                        }
763
764                        for field in &variant.fields {
765                            let field = field.did.expect_local();
766                            self.update(field, variant_ev, Level::Reachable);
767                            self.reach(field, variant_ev).ty();
768                        }
769                        // Corner case: if the variant is reachable, but its
770                        // enum is not, make the enum reachable as well.
771                        self.reach(owner_id.def_id, variant_ev).ty();
772                    }
773                    if let Some(ctor_def_id) = variant.ctor_def_id() {
774                        if let Some(ctor_ev) = self.get(ctor_def_id.expect_local()) {
775                            self.reach(owner_id.def_id, ctor_ev).ty();
776                        }
777                    }
778                }
779            }
780            DefKind::Struct | DefKind::Union => {
781                let def = self.tcx.adt_def(owner_id).non_enum_variant();
782                if let Some(item_ev) = item_ev {
783                    self.reach(owner_id.def_id, item_ev).generics().predicates();
784                    for field in &def.fields {
785                        let field = field.did.expect_local();
786                        self.update(field, item_ev, Level::Reachable);
787                        if let Some(field_ev) = self.get(field) {
788                            self.reach(field, field_ev).ty();
789                        }
790                    }
791                }
792                if let Some(ctor_def_id) = def.ctor_def_id() {
793                    if let Some(item_ev) = item_ev {
794                        self.update(ctor_def_id.expect_local(), item_ev, Level::Reachable);
795                    }
796                    if let Some(ctor_ev) = self.get(ctor_def_id.expect_local()) {
797                        self.reach(owner_id.def_id, ctor_ev).ty();
798                    }
799                }
800            }
801            // Contents are checked directly.
802            DefKind::ForeignMod => {}
803            DefKind::Field
804            | DefKind::Variant
805            | DefKind::AssocFn
806            | DefKind::AssocTy
807            | DefKind::AssocConst { .. }
808            | DefKind::TyParam
809            | DefKind::AnonConst
810            | DefKind::InlineConst
811            | DefKind::OpaqueTy
812            | DefKind::Closure
813            | DefKind::SyntheticCoroutineBody
814            | DefKind::ConstParam
815            | DefKind::LifetimeParam
816            | DefKind::Ctor(..) => {
817                ::rustc_middle::util::bug::bug_fmt(format_args!("should be checked while checking parent"))bug!("should be checked while checking parent")
818            }
819        }
820    }
821}
822
823impl ReachEverythingInTheInterfaceVisitor<'_, '_> {
824    fn generics(&mut self) -> &mut Self {
825        for param in &self.ev.tcx.generics_of(self.item_def_id).own_params {
826            if let GenericParamDefKind::Const { .. } = param.kind {
827                self.visit(self.ev.tcx.type_of(param.def_id).instantiate_identity());
828            }
829            if let Some(default) = param.default_value(self.ev.tcx) {
830                self.visit(default.instantiate_identity());
831            }
832        }
833        self
834    }
835
836    fn predicates(&mut self) -> &mut Self {
837        self.visit_predicates(self.ev.tcx.explicit_predicates_of(self.item_def_id));
838        self
839    }
840
841    fn bounds(&mut self) -> &mut Self {
842        self.visit_clauses(self.ev.tcx.explicit_item_bounds(self.item_def_id).skip_binder());
843        self
844    }
845
846    fn ty(&mut self) -> &mut Self {
847        self.visit(self.ev.tcx.type_of(self.item_def_id).instantiate_identity());
848        self
849    }
850
851    fn trait_ref(&mut self) -> &mut Self {
852        self.visit_trait(self.ev.tcx.impl_trait_ref(self.item_def_id).instantiate_identity());
853        self
854    }
855}
856
857impl<'tcx> DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
858    fn tcx(&self) -> TyCtxt<'tcx> {
859        self.ev.tcx
860    }
861    fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) {
862        if let Some(def_id) = def_id.as_local() {
863            // All effective visibilities except `reachable_through_impl_trait` are limited to
864            // nominal visibility. If any type or trait is leaked farther than that, it will
865            // produce type privacy errors on any use, so we don't consider it leaked.
866            let max_vis = (self.level != Level::ReachableThroughImplTrait)
867                .then(|| self.ev.tcx.local_visibility(def_id));
868            self.ev.update_eff_vis(def_id, self.effective_vis, max_vis, self.level);
869        }
870    }
871}
872
873/// Visitor, used for EffectiveVisibilities table checking
874pub struct TestReachabilityVisitor<'a, 'tcx> {
875    tcx: TyCtxt<'tcx>,
876    effective_visibilities: &'a EffectiveVisibilities,
877}
878
879impl<'a, 'tcx> TestReachabilityVisitor<'a, 'tcx> {
880    fn effective_visibility_diagnostic(&self, def_id: LocalDefId) {
881        if {

        #[allow(deprecated)]
        {
            {
                'done:
                    {
                    for i in self.tcx.get_all_attrs(def_id) {
                        #[allow(unused_imports)]
                        use rustc_hir::attrs::AttributeKind::*;
                        let i: &rustc_hir::Attribute = i;
                        match i {
                            rustc_hir::Attribute::Parsed(RustcEffectiveVisibility) => {
                                break 'done Some(());
                            }
                            rustc_hir::Attribute::Unparsed(..) =>
                                {}
                                #[deny(unreachable_patterns)]
                                _ => {}
                        }
                    }
                    None
                }
            }
        }
    }.is_some()find_attr!(self.tcx, def_id, RustcEffectiveVisibility) {
882            let mut error_msg = String::new();
883            let span = self.tcx.def_span(def_id.to_def_id());
884            if let Some(effective_vis) = self.effective_visibilities.effective_vis(def_id) {
885                for level in Level::all_levels() {
886                    let vis_str = effective_vis.at_level(level).to_string(def_id, self.tcx);
887                    if level != Level::Direct {
888                        error_msg.push_str(", ");
889                    }
890                    error_msg.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}: {1}", level, vis_str))
    })format!("{level:?}: {vis_str}"));
891                }
892            } else {
893                error_msg.push_str("not in the table");
894            }
895            self.tcx.dcx().emit_err(ReportEffectiveVisibility { span, descr: error_msg });
896        }
897    }
898}
899
900impl<'a, 'tcx> TestReachabilityVisitor<'a, 'tcx> {
901    fn check_def_id(&self, owner_id: OwnerId) {
902        self.effective_visibility_diagnostic(owner_id.def_id);
903
904        match self.tcx.def_kind(owner_id) {
905            DefKind::Enum => {
906                let def = self.tcx.adt_def(owner_id.def_id);
907                for variant in def.variants() {
908                    self.effective_visibility_diagnostic(variant.def_id.expect_local());
909                    if let Some(ctor_def_id) = variant.ctor_def_id() {
910                        self.effective_visibility_diagnostic(ctor_def_id.expect_local());
911                    }
912                    for field in &variant.fields {
913                        self.effective_visibility_diagnostic(field.did.expect_local());
914                    }
915                }
916            }
917            DefKind::Struct | DefKind::Union => {
918                let def = self.tcx.adt_def(owner_id.def_id).non_enum_variant();
919                if let Some(ctor_def_id) = def.ctor_def_id() {
920                    self.effective_visibility_diagnostic(ctor_def_id.expect_local());
921                }
922                for field in &def.fields {
923                    self.effective_visibility_diagnostic(field.did.expect_local());
924                }
925            }
926            _ => {}
927        }
928    }
929}
930
931/// Name privacy visitor, checks privacy and reports violations.
932///
933/// Most of name privacy checks are performed during the main resolution phase,
934/// or later in type checking when field accesses and associated items are resolved.
935/// This pass performs remaining checks for fields in struct expressions and patterns.
936struct NamePrivacyVisitor<'tcx> {
937    tcx: TyCtxt<'tcx>,
938    maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
939}
940
941impl<'tcx> NamePrivacyVisitor<'tcx> {
942    /// Gets the type-checking results for the current body.
943    /// As this will ICE if called outside bodies, only call when working with
944    /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
945    #[track_caller]
946    fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
947        self.maybe_typeck_results
948            .expect("`NamePrivacyVisitor::typeck_results` called outside of body")
949    }
950
951    // Checks that a field in a struct constructor (expression or pattern) is accessible.
952    fn check_field(
953        &self,
954        hir_id: hir::HirId,    // ID of the field use
955        use_ctxt: Span,        // syntax context of the field name at the use site
956        def: ty::AdtDef<'tcx>, // definition of the struct or enum
957        field: &'tcx ty::FieldDef,
958    ) -> bool {
959        if def.is_enum() {
960            return true;
961        }
962
963        // definition of the field
964        let ident = Ident::new(sym::dummy, use_ctxt);
965        let (_, def_id) = self.tcx.adjust_ident_and_get_scope(ident, def.did(), hir_id);
966        !field.vis.is_accessible_from(def_id, self.tcx)
967    }
968
969    // Checks that a field in a struct constructor (expression or pattern) is accessible.
970    fn emit_unreachable_field_error(
971        &self,
972        fields: Vec<(Symbol, Span, bool /* field is present */)>,
973        def: ty::AdtDef<'tcx>, // definition of the struct or enum
974        update_syntax: Option<Span>,
975        struct_span: Span,
976    ) {
977        if def.is_enum() || fields.is_empty() {
978            return;
979        }
980
981        //   error[E0451]: fields `beta` and `gamma` of struct `Alpha` are private
982        //   --> $DIR/visibility.rs:18:13
983        //    |
984        // LL |     let _x = Alpha {
985        //    |              ----- in this type      # from `def`
986        // LL |         beta: 0,
987        //    |         ^^^^^^^ private field        # `fields.2` is `true`
988        // LL |         ..
989        //    |         ^^ field `gamma` is private  # `fields.2` is `false`
990
991        // Get the list of all private fields for the main message.
992        let Some(field_names) = listify(&fields[..], |(n, _, _)| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", n))
    })format!("`{n}`")) else { return };
993        let span: MultiSpan = fields.iter().map(|(_, span, _)| *span).collect::<Vec<Span>>().into();
994
995        // Get the list of all private fields when pointing at the `..rest`.
996        let rest_field_names: Vec<_> =
997            fields.iter().filter(|(_, _, is_present)| !is_present).map(|(n, _, _)| n).collect();
998        let rest_len = rest_field_names.len();
999        let rest_field_names =
1000            listify(&rest_field_names[..], |n| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", n))
    })format!("`{n}`")).unwrap_or_default();
1001        // Get all the labels for each field or `..rest` in the primary MultiSpan.
1002        let labels = fields
1003            .iter()
1004            .filter(|(_, _, is_present)| *is_present)
1005            .map(|(_, span, _)| FieldIsPrivateLabel::Other { span: *span })
1006            .chain(update_syntax.iter().map(|span| FieldIsPrivateLabel::IsUpdateSyntax {
1007                span: *span,
1008                rest_field_names: rest_field_names.clone(),
1009                rest_len,
1010            }))
1011            .collect();
1012
1013        self.tcx.dcx().emit_err(FieldIsPrivate {
1014            span,
1015            struct_span: if self
1016                .tcx
1017                .sess
1018                .source_map()
1019                .is_multiline(fields[0].1.between(struct_span))
1020            {
1021                Some(struct_span)
1022            } else {
1023                None
1024            },
1025            field_names,
1026            variant_descr: def.variant_descr(),
1027            def_path_str: self.tcx.def_path_str(def.did()),
1028            labels,
1029            len: fields.len(),
1030        });
1031    }
1032
1033    fn check_expanded_fields(
1034        &self,
1035        adt: ty::AdtDef<'tcx>,
1036        variant: &'tcx ty::VariantDef,
1037        fields: &[hir::ExprField<'tcx>],
1038        hir_id: hir::HirId,
1039        span: Span,
1040        struct_span: Span,
1041    ) {
1042        let mut failed_fields = ::alloc::vec::Vec::new()vec![];
1043        for (vf_index, variant_field) in variant.fields.iter_enumerated() {
1044            let field =
1045                fields.iter().find(|f| self.typeck_results().field_index(f.hir_id) == vf_index);
1046            let (hir_id, use_ctxt, span) = match field {
1047                Some(field) => (field.hir_id, field.ident.span, field.span),
1048                None => (hir_id, span, span),
1049            };
1050            if self.check_field(hir_id, use_ctxt, adt, variant_field) {
1051                let name = match field {
1052                    Some(field) => field.ident.name,
1053                    None => variant_field.name,
1054                };
1055                failed_fields.push((name, span, field.is_some()));
1056            }
1057        }
1058        self.emit_unreachable_field_error(failed_fields, adt, Some(span), struct_span);
1059    }
1060}
1061
1062impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> {
1063    fn visit_nested_body(&mut self, body_id: hir::BodyId) {
1064        let new_typeck_results = self.tcx.typeck_body(body_id);
1065        // Do not try reporting privacy violations if we failed to infer types.
1066        if new_typeck_results.tainted_by_errors.is_some() {
1067            return;
1068        }
1069        let old_maybe_typeck_results = self.maybe_typeck_results.replace(new_typeck_results);
1070        self.visit_body(self.tcx.hir_body(body_id));
1071        self.maybe_typeck_results = old_maybe_typeck_results;
1072    }
1073
1074    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1075        if let hir::ExprKind::Struct(qpath, fields, ref base) = expr.kind {
1076            let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
1077            let adt = self.typeck_results().expr_ty(expr).ty_adt_def().unwrap();
1078            let variant = adt.variant_of_res(res);
1079            match *base {
1080                hir::StructTailExpr::Base(base) => {
1081                    // If the expression uses FRU we need to make sure all the unmentioned fields
1082                    // are checked for privacy (RFC 736). Rather than computing the set of
1083                    // unmentioned fields, just check them all.
1084                    self.check_expanded_fields(
1085                        adt,
1086                        variant,
1087                        fields,
1088                        base.hir_id,
1089                        base.span,
1090                        qpath.span(),
1091                    );
1092                }
1093                hir::StructTailExpr::DefaultFields(span) => {
1094                    self.check_expanded_fields(
1095                        adt,
1096                        variant,
1097                        fields,
1098                        expr.hir_id,
1099                        span,
1100                        qpath.span(),
1101                    );
1102                }
1103                hir::StructTailExpr::None | hir::StructTailExpr::NoneWithError(_) => {
1104                    let mut failed_fields = ::alloc::vec::Vec::new()vec![];
1105                    for field in fields {
1106                        let (hir_id, use_ctxt) = (field.hir_id, field.ident.span);
1107                        let index = self.typeck_results().field_index(field.hir_id);
1108                        if self.check_field(hir_id, use_ctxt, adt, &variant.fields[index]) {
1109                            failed_fields.push((field.ident.name, field.ident.span, true));
1110                        }
1111                    }
1112                    self.emit_unreachable_field_error(failed_fields, adt, None, qpath.span());
1113                }
1114            }
1115        }
1116
1117        intravisit::walk_expr(self, expr);
1118    }
1119
1120    fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
1121        if let PatKind::Struct(ref qpath, fields, _) = pat.kind {
1122            let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
1123            let adt = self.typeck_results().pat_ty(pat).ty_adt_def().unwrap();
1124            let variant = adt.variant_of_res(res);
1125            let mut failed_fields = ::alloc::vec::Vec::new()vec![];
1126            for field in fields {
1127                let (hir_id, use_ctxt) = (field.hir_id, field.ident.span);
1128                let index = self.typeck_results().field_index(field.hir_id);
1129                if self.check_field(hir_id, use_ctxt, adt, &variant.fields[index]) {
1130                    failed_fields.push((field.ident.name, field.ident.span, true));
1131                }
1132            }
1133            self.emit_unreachable_field_error(failed_fields, adt, None, qpath.span());
1134        }
1135
1136        intravisit::walk_pat(self, pat);
1137    }
1138}
1139
1140/// Type privacy visitor, checks types for privacy and reports violations.
1141///
1142/// Both explicitly written types and inferred types of expressions and patterns are checked.
1143/// Checks are performed on "semantic" types regardless of names and their hygiene.
1144struct TypePrivacyVisitor<'tcx> {
1145    tcx: TyCtxt<'tcx>,
1146    module_def_id: LocalModDefId,
1147    maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
1148    span: Span,
1149}
1150
1151impl<'tcx> TypePrivacyVisitor<'tcx> {
1152    fn item_is_accessible(&self, did: DefId) -> bool {
1153        self.tcx.visibility(did).is_accessible_from(self.module_def_id, self.tcx)
1154    }
1155
1156    // Take node-id of an expression or pattern and check its type for privacy.
1157    fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
1158        self.span = span;
1159        let typeck_results = self
1160            .maybe_typeck_results
1161            .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("`hir::Expr` or `hir::Pat` outside of a body"))span_bug!(span, "`hir::Expr` or `hir::Pat` outside of a body"));
1162        try {
1163            self.visit(typeck_results.node_type(id))?;
1164            self.visit(typeck_results.node_args(id))?;
1165            if let Some(adjustments) = typeck_results.adjustments().get(id) {
1166                adjustments.iter().try_for_each(|adjustment| self.visit(adjustment.target))?;
1167            }
1168        }
1169        .is_break()
1170    }
1171
1172    fn check_def_id(&self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1173        let is_error = !self.item_is_accessible(def_id);
1174        if is_error {
1175            self.tcx.dcx().emit_err(ItemIsPrivate { span: self.span, kind, descr: descr.into() });
1176        }
1177        is_error
1178    }
1179}
1180
1181impl<'tcx> rustc_ty_utils::sig_types::SpannedTypeVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1182    type Result = ControlFlow<()>;
1183    fn visit(&mut self, span: Span, value: impl TypeVisitable<TyCtxt<'tcx>>) -> Self::Result {
1184        self.span = span;
1185        value.visit_with(&mut self.skeleton())
1186    }
1187}
1188
1189impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> {
1190    fn visit_nested_body(&mut self, body_id: hir::BodyId) {
1191        let old_maybe_typeck_results =
1192            self.maybe_typeck_results.replace(self.tcx.typeck_body(body_id));
1193        self.visit_body(self.tcx.hir_body(body_id));
1194        self.maybe_typeck_results = old_maybe_typeck_results;
1195    }
1196
1197    fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx, AmbigArg>) {
1198        self.span = hir_ty.span;
1199        if self
1200            .visit(
1201                self.maybe_typeck_results
1202                    .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(hir_ty.span,
    format_args!("`hir::Ty` outside of a body"))span_bug!(hir_ty.span, "`hir::Ty` outside of a body"))
1203                    .node_type(hir_ty.hir_id),
1204            )
1205            .is_break()
1206        {
1207            return;
1208        }
1209
1210        intravisit::walk_ty(self, hir_ty);
1211    }
1212
1213    fn visit_infer(
1214        &mut self,
1215        inf_id: rustc_hir::HirId,
1216        inf_span: Span,
1217        _kind: InferKind<'tcx>,
1218    ) -> Self::Result {
1219        self.span = inf_span;
1220        if let Some(ty) = self
1221            .maybe_typeck_results
1222            .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(inf_span,
    format_args!("Inference variable outside of a body"))span_bug!(inf_span, "Inference variable outside of a body"))
1223            .node_type_opt(inf_id)
1224        {
1225            if self.visit(ty).is_break() {
1226                return;
1227            }
1228        } else {
1229            // FIXME: check types of const infers here.
1230        }
1231
1232        self.visit_id(inf_id)
1233    }
1234
1235    // Check types of expressions
1236    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1237        if self.check_expr_pat_type(expr.hir_id, expr.span) {
1238            // Do not check nested expressions if the error already happened.
1239            return;
1240        }
1241        match expr.kind {
1242            hir::ExprKind::Assign(_, rhs, _) | hir::ExprKind::Match(rhs, ..) => {
1243                // Do not report duplicate errors for `x = y` and `match x { ... }`.
1244                if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
1245                    return;
1246                }
1247            }
1248            hir::ExprKind::MethodCall(segment, ..) => {
1249                // Method calls have to be checked specially.
1250                self.span = segment.ident.span;
1251                let typeck_results = self
1252                    .maybe_typeck_results
1253                    .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(self.span,
    format_args!("`hir::Expr` outside of a body"))span_bug!(self.span, "`hir::Expr` outside of a body"));
1254                if let Some(def_id) = typeck_results.type_dependent_def_id(expr.hir_id) {
1255                    if self.visit(self.tcx.type_of(def_id).instantiate_identity()).is_break() {
1256                        return;
1257                    }
1258                } else {
1259                    self.tcx
1260                        .dcx()
1261                        .span_delayed_bug(expr.span, "no type-dependent def for method call");
1262                }
1263            }
1264            _ => {}
1265        }
1266
1267        intravisit::walk_expr(self, expr);
1268    }
1269
1270    // Prohibit access to associated items with insufficient nominal visibility.
1271    //
1272    // Additionally, until better reachability analysis for macros 2.0 is available,
1273    // we prohibit access to private statics from other crates, this allows to give
1274    // more code internal visibility at link time. (Access to private functions
1275    // is already prohibited by type privacy for function types.)
1276    fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) {
1277        let def = match qpath {
1278            hir::QPath::Resolved(_, path) => match path.res {
1279                Res::Def(kind, def_id) => Some((kind, def_id)),
1280                _ => None,
1281            },
1282            hir::QPath::TypeRelative(..) => {
1283                match self.maybe_typeck_results {
1284                    Some(typeck_results) => typeck_results.type_dependent_def(id),
1285                    // FIXME: Check type-relative associated types in signatures.
1286                    None => None,
1287                }
1288            }
1289        };
1290        let def = def.filter(|(kind, _)| {
1291            #[allow(non_exhaustive_omitted_patterns)] match kind {
    DefKind::AssocFn | DefKind::AssocConst { .. } | DefKind::AssocTy |
        DefKind::Static { .. } => true,
    _ => false,
}matches!(
1292                kind,
1293                DefKind::AssocFn
1294                    | DefKind::AssocConst { .. }
1295                    | DefKind::AssocTy
1296                    | DefKind::Static { .. }
1297            )
1298        });
1299        if let Some((kind, def_id)) = def {
1300            let is_local_static =
1301                if let DefKind::Static { .. } = kind { def_id.is_local() } else { false };
1302            if !self.item_is_accessible(def_id) && !is_local_static {
1303                let name = match *qpath {
1304                    hir::QPath::Resolved(_, path) => Some(self.tcx.def_path_str(path.res.def_id())),
1305                    hir::QPath::TypeRelative(_, segment) => Some(segment.ident.to_string()),
1306                };
1307                let kind = self.tcx.def_descr(def_id);
1308                let sess = self.tcx.sess;
1309                let _ = match name {
1310                    Some(name) => {
1311                        sess.dcx().emit_err(ItemIsPrivate { span, kind, descr: (&name).into() })
1312                    }
1313                    None => sess.dcx().emit_err(UnnamedItemIsPrivate { span, kind }),
1314                };
1315                return;
1316            }
1317        }
1318
1319        intravisit::walk_qpath(self, qpath, id);
1320    }
1321
1322    // Check types of patterns.
1323    fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) {
1324        if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
1325            // Do not check nested patterns if the error already happened.
1326            return;
1327        }
1328
1329        intravisit::walk_pat(self, pattern);
1330    }
1331
1332    fn visit_local(&mut self, local: &'tcx hir::LetStmt<'tcx>) {
1333        if let Some(init) = local.init {
1334            if self.check_expr_pat_type(init.hir_id, init.span) {
1335                // Do not report duplicate errors for `let x = y`.
1336                return;
1337            }
1338        }
1339
1340        intravisit::walk_local(self, local);
1341    }
1342}
1343
1344impl<'tcx> DefIdVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1345    type Result = ControlFlow<()>;
1346    fn tcx(&self) -> TyCtxt<'tcx> {
1347        self.tcx
1348    }
1349    fn visit_def_id(
1350        &mut self,
1351        def_id: DefId,
1352        kind: &str,
1353        descr: &dyn fmt::Display,
1354    ) -> Self::Result {
1355        if self.check_def_id(def_id, kind, descr) {
1356            ControlFlow::Break(())
1357        } else {
1358            ControlFlow::Continue(())
1359        }
1360    }
1361}
1362
1363/// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1364/// finds any private components in it.
1365///
1366/// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1367/// and traits in public interfaces.
1368struct SearchInterfaceForPrivateItemsVisitor<'tcx> {
1369    tcx: TyCtxt<'tcx>,
1370    item_def_id: LocalDefId,
1371    /// The visitor checks that each component type is at least this visible.
1372    required_visibility: ty::Visibility,
1373    required_effective_vis: Option<EffectiveVisibility>,
1374    hard_error: bool = false,
1375    in_primary_interface: bool = true,
1376    skip_assoc_tys: bool = false,
1377}
1378
1379impl SearchInterfaceForPrivateItemsVisitor<'_> {
1380    fn generics(&mut self) -> &mut Self {
1381        self.in_primary_interface = true;
1382        for param in &self.tcx.generics_of(self.item_def_id).own_params {
1383            if let GenericParamDefKind::Const { .. } = param.kind {
1384                let _ = self.visit(self.tcx.type_of(param.def_id).instantiate_identity());
1385            }
1386            if let Some(default) = param.default_value(self.tcx) {
1387                let _ = self.visit(default.instantiate_identity());
1388            }
1389        }
1390        self
1391    }
1392
1393    fn predicates(&mut self) -> &mut Self {
1394        self.in_primary_interface = false;
1395        // N.B., we use `explicit_predicates_of` and not `predicates_of`
1396        // because we don't want to report privacy errors due to where
1397        // clauses that the compiler inferred. We only want to
1398        // consider the ones that the user wrote. This is important
1399        // for the inferred outlives rules; see
1400        // `tests/ui/rfc-2093-infer-outlives/privacy.rs`.
1401        let _ = self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id));
1402        self
1403    }
1404
1405    fn bounds(&mut self) -> &mut Self {
1406        self.in_primary_interface = false;
1407        let _ = self.visit_clauses(self.tcx.explicit_item_bounds(self.item_def_id).skip_binder());
1408        self
1409    }
1410
1411    fn ty(&mut self) -> &mut Self {
1412        self.in_primary_interface = true;
1413        let _ = self.visit(self.tcx.type_of(self.item_def_id).instantiate_identity());
1414        self
1415    }
1416
1417    fn trait_ref(&mut self) -> &mut Self {
1418        self.in_primary_interface = true;
1419        let _ = self.visit_trait(self.tcx.impl_trait_ref(self.item_def_id).instantiate_identity());
1420        self
1421    }
1422
1423    fn check_def_id(&self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1424        if self.leaks_private_dep(def_id) {
1425            self.tcx.emit_node_span_lint(
1426                lint::builtin::EXPORTED_PRIVATE_DEPENDENCIES,
1427                self.tcx.local_def_id_to_hir_id(self.item_def_id),
1428                self.tcx.def_span(self.item_def_id.to_def_id()),
1429                FromPrivateDependencyInPublicInterface {
1430                    kind,
1431                    descr: descr.into(),
1432                    krate: self.tcx.crate_name(def_id.krate),
1433                },
1434            );
1435        }
1436
1437        let Some(local_def_id) = def_id.as_local() else {
1438            return false;
1439        };
1440
1441        let vis = self.tcx.local_visibility(local_def_id);
1442        if self.hard_error && !vis.is_at_least(self.required_visibility, self.tcx) {
1443            let vis_descr = match vis {
1444                ty::Visibility::Public => "public",
1445                ty::Visibility::Restricted(vis_def_id) => {
1446                    if vis_def_id
1447                        == self.tcx.parent_module_from_def_id(local_def_id).to_local_def_id()
1448                    {
1449                        "private"
1450                    } else if vis_def_id.is_top_level_module() {
1451                        "crate-private"
1452                    } else {
1453                        "restricted"
1454                    }
1455                }
1456            };
1457
1458            let span = self.tcx.def_span(self.item_def_id.to_def_id());
1459            let vis_span = self.tcx.def_span(def_id);
1460            self.tcx.dcx().emit_err(InPublicInterface {
1461                span,
1462                vis_descr,
1463                kind,
1464                descr: descr.into(),
1465                vis_span,
1466            });
1467            return false;
1468        }
1469
1470        let Some(effective_vis) = self.required_effective_vis else {
1471            return false;
1472        };
1473
1474        let reachable_at_vis = *effective_vis.at_level(Level::Reachable);
1475
1476        if !vis.is_at_least(reachable_at_vis, self.tcx) {
1477            let lint = if self.in_primary_interface {
1478                lint::builtin::PRIVATE_INTERFACES
1479            } else {
1480                lint::builtin::PRIVATE_BOUNDS
1481            };
1482            let span = self.tcx.def_span(self.item_def_id.to_def_id());
1483            let vis_span = self.tcx.def_span(def_id);
1484            self.tcx.emit_node_span_lint(
1485                lint,
1486                self.tcx.local_def_id_to_hir_id(self.item_def_id),
1487                span,
1488                PrivateInterfacesOrBoundsLint {
1489                    item_span: span,
1490                    item_kind: self.tcx.def_descr(self.item_def_id.to_def_id()),
1491                    item_descr: (&LazyDefPathStr {
1492                        def_id: self.item_def_id.to_def_id(),
1493                        tcx: self.tcx,
1494                    })
1495                        .into(),
1496                    item_vis_descr: &reachable_at_vis.to_string(self.item_def_id, self.tcx),
1497                    ty_span: vis_span,
1498                    ty_kind: kind,
1499                    ty_descr: descr.into(),
1500                    ty_vis_descr: &vis.to_string(local_def_id, self.tcx),
1501                },
1502            );
1503        }
1504
1505        false
1506    }
1507
1508    /// An item is 'leaked' from a private dependency if all
1509    /// of the following are true:
1510    /// 1. It's contained within a public type
1511    /// 2. It comes from a private crate
1512    fn leaks_private_dep(&self, item_id: DefId) -> bool {
1513        let ret = self.required_visibility.is_public() && self.tcx.is_private_dep(item_id.krate);
1514
1515        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_privacy/src/lib.rs:1515",
                        "rustc_privacy", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_privacy/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1515u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_privacy"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("leaks_private_dep(item_id={0:?})={1}",
                                                    item_id, ret) as &dyn Value))])
            });
    } else { ; }
};debug!("leaks_private_dep(item_id={:?})={}", item_id, ret);
1516        ret
1517    }
1518}
1519
1520impl<'tcx> DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> {
1521    type Result = ControlFlow<()>;
1522    fn skip_assoc_tys(&self) -> bool {
1523        self.skip_assoc_tys
1524    }
1525    fn tcx(&self) -> TyCtxt<'tcx> {
1526        self.tcx
1527    }
1528    fn visit_def_id(
1529        &mut self,
1530        def_id: DefId,
1531        kind: &str,
1532        descr: &dyn fmt::Display,
1533    ) -> Self::Result {
1534        if self.check_def_id(def_id, kind, descr) {
1535            ControlFlow::Break(())
1536        } else {
1537            ControlFlow::Continue(())
1538        }
1539    }
1540}
1541
1542struct PrivateItemsInPublicInterfacesChecker<'a, 'tcx> {
1543    tcx: TyCtxt<'tcx>,
1544    effective_visibilities: &'a EffectiveVisibilities,
1545}
1546
1547impl<'tcx> PrivateItemsInPublicInterfacesChecker<'_, 'tcx> {
1548    fn check(
1549        &self,
1550        def_id: LocalDefId,
1551        required_visibility: ty::Visibility,
1552        required_effective_vis: Option<EffectiveVisibility>,
1553    ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> {
1554        SearchInterfaceForPrivateItemsVisitor {
1555            tcx: self.tcx,
1556            item_def_id: def_id,
1557            required_visibility,
1558            required_effective_vis,
1559            ..
1560        }
1561    }
1562
1563    fn check_unnameable(&self, def_id: LocalDefId, effective_vis: Option<EffectiveVisibility>) {
1564        let Some(effective_vis) = effective_vis else {
1565            return;
1566        };
1567
1568        let reexported_at_vis = effective_vis.at_level(Level::Reexported);
1569        let reachable_at_vis = effective_vis.at_level(Level::Reachable);
1570
1571        if reachable_at_vis.is_public() && reexported_at_vis != reachable_at_vis {
1572            let hir_id = self.tcx.local_def_id_to_hir_id(def_id);
1573            let span = self.tcx.def_span(def_id.to_def_id());
1574            self.tcx.emit_node_span_lint(
1575                lint::builtin::UNNAMEABLE_TYPES,
1576                hir_id,
1577                span,
1578                UnnameableTypesLint {
1579                    span,
1580                    kind: self.tcx.def_descr(def_id.to_def_id()),
1581                    descr: (&LazyDefPathStr { def_id: def_id.to_def_id(), tcx: self.tcx }).into(),
1582                    reachable_vis: &reachable_at_vis.to_string(def_id, self.tcx),
1583                    reexported_vis: &reexported_at_vis.to_string(def_id, self.tcx),
1584                },
1585            );
1586        }
1587    }
1588
1589    fn check_assoc_item(
1590        &self,
1591        item: &ty::AssocItem,
1592        vis: ty::Visibility,
1593        effective_vis: Option<EffectiveVisibility>,
1594    ) {
1595        let mut check = self.check(item.def_id.expect_local(), vis, effective_vis);
1596
1597        let is_assoc_ty = item.is_type();
1598        check.hard_error = is_assoc_ty && !item.is_impl_trait_in_trait();
1599        check.generics().predicates();
1600        if assoc_has_type_of(self.tcx, item) {
1601            check.hard_error = check.hard_error && item.defaultness(self.tcx).has_value();
1602            check.ty();
1603        }
1604        if is_assoc_ty && item.container == AssocContainer::Trait {
1605            check.hard_error = false;
1606            check.bounds();
1607        }
1608    }
1609
1610    fn get(&self, def_id: LocalDefId) -> Option<EffectiveVisibility> {
1611        self.effective_visibilities.effective_vis(def_id).copied()
1612    }
1613
1614    fn check_item(&self, id: ItemId) {
1615        let tcx = self.tcx;
1616        let def_id = id.owner_id.def_id;
1617        let item_visibility = tcx.local_visibility(def_id);
1618        let effective_vis = self.get(def_id);
1619        let def_kind = tcx.def_kind(def_id);
1620
1621        match def_kind {
1622            DefKind::Const { .. } | DefKind::Static { .. } | DefKind::Fn | DefKind::TyAlias => {
1623                if let DefKind::TyAlias = def_kind {
1624                    self.check_unnameable(def_id, effective_vis);
1625                }
1626                self.check(def_id, item_visibility, effective_vis).generics().predicates().ty();
1627            }
1628            DefKind::OpaqueTy => {
1629                // `ty()` for opaque types is the underlying type,
1630                // it's not a part of interface, so we skip it.
1631                self.check(def_id, item_visibility, effective_vis).generics().bounds();
1632            }
1633            DefKind::Trait => {
1634                self.check_unnameable(def_id, effective_vis);
1635
1636                self.check(def_id, item_visibility, effective_vis).generics().predicates();
1637
1638                for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() {
1639                    self.check_assoc_item(assoc_item, item_visibility, effective_vis);
1640                }
1641            }
1642            DefKind::TraitAlias => {
1643                self.check(def_id, item_visibility, effective_vis).generics().predicates();
1644            }
1645            DefKind::Enum => {
1646                self.check_unnameable(def_id, effective_vis);
1647                self.check(def_id, item_visibility, effective_vis).generics().predicates();
1648
1649                let adt = tcx.adt_def(id.owner_id);
1650                for field in adt.all_fields() {
1651                    self.check(field.did.expect_local(), item_visibility, effective_vis).ty();
1652                }
1653            }
1654            // Subitems of structs and unions have their own publicity.
1655            DefKind::Struct | DefKind::Union => {
1656                self.check_unnameable(def_id, effective_vis);
1657                self.check(def_id, item_visibility, effective_vis).generics().predicates();
1658
1659                let adt = tcx.adt_def(id.owner_id);
1660                for field in adt.all_fields() {
1661                    let visibility = min(item_visibility, field.vis.expect_local(), tcx);
1662                    let field_ev = self.get(field.did.expect_local());
1663
1664                    self.check(field.did.expect_local(), visibility, field_ev).ty();
1665                }
1666            }
1667            // Subitems of foreign modules have their own publicity.
1668            DefKind::ForeignMod => {}
1669            // An inherent impl is public when its type is public
1670            // Subitems of inherent impls have their own publicity.
1671            // A trait impl is public when both its type and its trait are public
1672            // Subitems of trait impls have inherited publicity.
1673            DefKind::Impl { of_trait } => {
1674                let impl_vis =
1675                    ty::Visibility::of_impl::<false>(def_id, of_trait, tcx, &Default::default());
1676
1677                // We are using the non-shallow version here, unlike when building the
1678                // effective visisibilities table to avoid large number of false positives.
1679                // For example in
1680                //
1681                // impl From<Priv> for Pub {
1682                //     fn from(_: Priv) -> Pub {...}
1683                // }
1684                //
1685                // lints shouldn't be emitted even if `from` effective visibility
1686                // is larger than `Priv` nominal visibility and if `Priv` can leak
1687                // in some scenarios due to type inference.
1688                let impl_ev = EffectiveVisibility::of_impl::<false>(
1689                    def_id,
1690                    of_trait,
1691                    tcx,
1692                    self.effective_visibilities,
1693                );
1694
1695                let mut check = self.check(def_id, impl_vis, Some(impl_ev));
1696
1697                // Generics and predicates of trait impls are intentionally not checked
1698                // for private components (#90586).
1699                if !of_trait {
1700                    check.generics().predicates();
1701                }
1702
1703                // Skip checking private components in associated types, due to lack of full
1704                // normalization they produce very ridiculous false positives.
1705                // FIXME: Remove this when full normalization is implemented.
1706                check.skip_assoc_tys = true;
1707                check.ty();
1708                if of_trait {
1709                    check.trait_ref();
1710                }
1711
1712                for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() {
1713                    let impl_item_vis = if !of_trait {
1714                        min(tcx.local_visibility(assoc_item.def_id.expect_local()), impl_vis, tcx)
1715                    } else {
1716                        impl_vis
1717                    };
1718
1719                    let impl_item_ev = if !of_trait {
1720                        self.get(assoc_item.def_id.expect_local())
1721                            .map(|ev| ev.min(impl_ev, self.tcx))
1722                    } else {
1723                        Some(impl_ev)
1724                    };
1725
1726                    self.check_assoc_item(assoc_item, impl_item_vis, impl_item_ev);
1727                }
1728            }
1729            _ => {}
1730        }
1731    }
1732
1733    fn check_foreign_item(&self, id: ForeignItemId) {
1734        let tcx = self.tcx;
1735        let def_id = id.owner_id.def_id;
1736        let item_visibility = tcx.local_visibility(def_id);
1737        let effective_vis = self.get(def_id);
1738
1739        if let DefKind::ForeignTy = self.tcx.def_kind(def_id) {
1740            self.check_unnameable(def_id, effective_vis);
1741        }
1742
1743        self.check(def_id, item_visibility, effective_vis).generics().predicates().ty();
1744    }
1745}
1746
1747pub fn provide(providers: &mut Providers) {
1748    *providers = Providers {
1749        effective_visibilities,
1750        check_private_in_public,
1751        check_mod_privacy,
1752        ..*providers
1753    };
1754}
1755
1756fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
1757    // Check privacy of names not checked in previous compilation stages.
1758    let mut visitor = NamePrivacyVisitor { tcx, maybe_typeck_results: None };
1759    tcx.hir_visit_item_likes_in_module(module_def_id, &mut visitor);
1760
1761    // Check privacy of explicitly written types and traits as well as
1762    // inferred types of expressions and patterns.
1763    let span = tcx.def_span(module_def_id);
1764    let mut visitor = TypePrivacyVisitor { tcx, module_def_id, maybe_typeck_results: None, span };
1765
1766    let module = tcx.hir_module_items(module_def_id);
1767    for def_id in module.definitions() {
1768        let _ = rustc_ty_utils::sig_types::walk_types(tcx, def_id, &mut visitor);
1769
1770        if let Some(body_id) = tcx.hir_maybe_body_owned_by(def_id) {
1771            visitor.visit_nested_body(body_id.id());
1772        }
1773
1774        if let DefKind::Impl { of_trait: true } = tcx.def_kind(def_id) {
1775            let trait_ref = tcx.impl_trait_ref(def_id);
1776            let trait_ref = trait_ref.instantiate_identity();
1777            visitor.span =
1778                tcx.hir_expect_item(def_id).expect_impl().of_trait.unwrap().trait_ref.path.span;
1779            let _ =
1780                visitor.visit_def_id(trait_ref.def_id, "trait", &trait_ref.print_only_trait_path());
1781        }
1782    }
1783}
1784
1785fn effective_visibilities(tcx: TyCtxt<'_>, (): ()) -> &EffectiveVisibilities {
1786    // Build up a set of all exported items in the AST. This is a set of all
1787    // items which are reachable from external crates based on visibility.
1788    let mut visitor = EmbargoVisitor {
1789        tcx,
1790        effective_visibilities: tcx.resolutions(()).effective_visibilities.clone(),
1791        macro_reachable: Default::default(),
1792        changed: false,
1793    };
1794
1795    visitor.effective_visibilities.check_invariants(tcx);
1796
1797    // HACK(jynelson): trying to infer the type of `impl Trait` breaks `async-std` (and
1798    // `pub async fn` in general). Since rustdoc never needs to do codegen and doesn't
1799    // care about link-time reachability, keep them unreachable (issue #75100).
1800    let impl_trait_pass = !tcx.sess.opts.actually_rustdoc;
1801    if impl_trait_pass {
1802        // Underlying types of `impl Trait`s are marked as reachable unconditionally,
1803        // so this pass doesn't need to be a part of the fixed point iteration below.
1804        let krate = tcx.hir_crate_items(());
1805        for id in krate.opaques() {
1806            let opaque = tcx.hir_node_by_def_id(id).expect_opaque_ty();
1807            let should_visit = match opaque.origin {
1808                hir::OpaqueTyOrigin::FnReturn {
1809                    parent,
1810                    in_trait_or_impl: Some(hir::RpitContext::Trait),
1811                }
1812                | hir::OpaqueTyOrigin::AsyncFn {
1813                    parent,
1814                    in_trait_or_impl: Some(hir::RpitContext::Trait),
1815                } => match tcx.hir_node_by_def_id(parent).expect_trait_item().expect_fn().1 {
1816                    hir::TraitFn::Required(_) => false,
1817                    hir::TraitFn::Provided(..) => true,
1818                },
1819
1820                // Always visit RPITs in functions that have definitions,
1821                // and all TAITs.
1822                hir::OpaqueTyOrigin::FnReturn {
1823                    in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
1824                    ..
1825                }
1826                | hir::OpaqueTyOrigin::AsyncFn {
1827                    in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
1828                    ..
1829                }
1830                | hir::OpaqueTyOrigin::TyAlias { .. } => true,
1831            };
1832            if should_visit {
1833                // FIXME: This is some serious pessimization intended to workaround deficiencies
1834                // in the reachability pass (`middle/reachable.rs`). Types are marked as link-time
1835                // reachable if they are returned via `impl Trait`, even from private functions.
1836                let pub_ev = EffectiveVisibility::from_vis(ty::Visibility::Public);
1837                visitor
1838                    .reach_through_impl_trait(opaque.def_id, pub_ev)
1839                    .generics()
1840                    .predicates()
1841                    .ty();
1842            }
1843        }
1844
1845        visitor.changed = false;
1846    }
1847
1848    let crate_items = tcx.hir_crate_items(());
1849    loop {
1850        for id in crate_items.free_items() {
1851            visitor.check_def_id(id.owner_id);
1852        }
1853        for id in crate_items.foreign_items() {
1854            visitor.check_def_id(id.owner_id);
1855        }
1856        if visitor.changed {
1857            visitor.changed = false;
1858        } else {
1859            break;
1860        }
1861    }
1862    visitor.effective_visibilities.check_invariants(tcx);
1863
1864    let check_visitor =
1865        TestReachabilityVisitor { tcx, effective_visibilities: &visitor.effective_visibilities };
1866    for id in crate_items.owners() {
1867        check_visitor.check_def_id(id);
1868    }
1869
1870    tcx.arena.alloc(visitor.effective_visibilities)
1871}
1872
1873fn check_private_in_public(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
1874    let effective_visibilities = tcx.effective_visibilities(());
1875    // Check for private types in public interfaces.
1876    let checker = PrivateItemsInPublicInterfacesChecker { tcx, effective_visibilities };
1877
1878    let crate_items = tcx.hir_module_items(module_def_id);
1879    let _ = crate_items.par_items(|id| Ok(checker.check_item(id)));
1880    let _ = crate_items.par_foreign_items(|id| Ok(checker.check_foreign_item(id)));
1881}