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 diagnostics;
8
9use std::marker::PhantomData;
10use std::ops::ControlFlow;
11use std::{debug_assert_matches, fmt};
12
13use diagnostics::{
14    FieldIsPrivate, FieldIsPrivateLabel, FromPrivateDependencyInPublicInterface, InPublicInterface,
15    ItemIsPrivate, PrivateInterfacesOrBoundsLint, ReportEffectiveVisibility, UnnameableTypesLint,
16    UnnamedItemIsPrivate,
17};
18use rustc_ast::visit::{VisitorResult, try_visit};
19use rustc_data_structures::fx::{FxHashMap, FxHashSet};
20use rustc_data_structures::indexmap::IndexSet;
21use rustc_data_structures::intern::Interned;
22use rustc_errors::{MultiSpan, listify};
23use rustc_hir::def::{CtorOf, DefKind, Res};
24use rustc_hir::def_id::{DefId, LocalDefId, LocalModId};
25use rustc_hir::intravisit::{self, InferKind, Visitor};
26use rustc_hir::{self as hir, AmbigArg, ForeignItemId, ItemId, OwnerId, PatKind, find_attr};
27use rustc_lint_defs::builtin::{
28    EXPORTED_PRIVATE_DEPENDENCIES, PRIVATE_BOUNDS, PRIVATE_INTERFACES, UNNAMEABLE_TYPES,
29};
30use rustc_middle::middle::privacy::{EffectiveVisibilities, EffectiveVisibility, Level};
31use rustc_middle::query::Providers;
32use rustc_middle::ty::print::PrintTraitRefExt as _;
33use rustc_middle::ty::{
34    self, AssocContainer, Const, GenericParamDefKind, PredicateProxy, TraitRef, Ty, TyCtxt,
35    TypeSuperVisitable, TypeVisitable, TypeVisitor,
36};
37use rustc_span::{Ident, Span, Symbol, bug, span_bug, sym};
38use tracing::debug;
39
40////////////////////////////////////////////////////////////////////////////////
41// Generic infrastructure used to implement specific visitors below.
42////////////////////////////////////////////////////////////////////////////////
43
44struct LazyDefPathStr<'tcx> {
45    def_id: DefId,
46    tcx: TyCtxt<'tcx>,
47}
48
49impl<'tcx> fmt::Display for LazyDefPathStr<'tcx> {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        f.write_fmt(format_args!("{0}", self.tcx.def_path_str(self.def_id)))write!(f, "{}", self.tcx.def_path_str(self.def_id))
52    }
53}
54
55/// Implemented to visit all `DefId`s in a type.
56/// Visiting `DefId`s is useful because visibilities and reachabilities are attached to them.
57/// The idea is to visit "all components of a type", as documented in
58/// <https://rust-lang.github.io/rfcs/2145-type-privacy.html#how-to-determine-visibility-of-a-type>.
59/// The default type visitor (`TypeVisitor`) does most of the job, but it has some shortcomings.
60/// First, it doesn't have overridable `fn visit_trait_ref`, so we have to catch trait `DefId`s
61/// manually. Second, it doesn't visit some type components like signatures of fn types, or traits
62/// in `impl Trait`, see individual comments in `DefIdVisitorSkeleton::visit_ty`.
63pub trait DefIdVisitor<'tcx> {
64    type Result: VisitorResult = ();
65    const SHALLOW: bool = false;
66    fn skip_assoc_tys(&self) -> bool {
67        false
68    }
69
70    fn tcx(&self) -> TyCtxt<'tcx>;
71    /// NOTE: Def-id visiting should be idempotent (or at least produce duplicated errors),
72    /// because `DefIdVisitorSkeleton` will use caching and sometimes avoid visiting duplicate
73    /// def-ids. All the current visitors follow this rule.
74    fn visit_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display)
75    -> Self::Result;
76
77    /// Not overridden, but used to actually visit types and traits.
78    fn skeleton(&mut self) -> DefIdVisitorSkeleton<'_, 'tcx, Self> {
79        DefIdVisitorSkeleton {
80            def_id_visitor: self,
81            visited_tys: Default::default(),
82            dummy: Default::default(),
83        }
84    }
85    fn visit(&mut self, ty_fragment: impl TypeVisitable<TyCtxt<'tcx>>) -> Self::Result {
86        ty_fragment.visit_with(&mut self.skeleton())
87    }
88    fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> Self::Result {
89        self.skeleton().visit_trait(trait_ref)
90    }
91    fn visit_gen_clauses(&mut self, gen_clauses: ty::GenericClauses<'tcx>) -> Self::Result {
92        self.skeleton().visit_clauses(gen_clauses.clauses)
93    }
94    fn visit_clauses(&mut self, clauses: &[(ty::Clause<'tcx>, Span)]) -> Self::Result {
95        self.skeleton().visit_clauses(clauses)
96    }
97}
98
99pub struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> {
100    def_id_visitor: &'v mut V,
101    visited_tys: FxHashSet<Ty<'tcx>>,
102    dummy: PhantomData<TyCtxt<'tcx>>,
103}
104
105impl<'tcx, V> DefIdVisitorSkeleton<'_, 'tcx, V>
106where
107    V: DefIdVisitor<'tcx> + ?Sized,
108{
109    fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> V::Result {
110        let TraitRef { def_id, args, .. } = trait_ref;
111        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(
112            def_id,
113            "trait",
114            &trait_ref.print_only_trait_path()
115        ));
116        if V::SHALLOW { V::Result::output() } else { args.visit_with(self) }
117    }
118
119    fn visit_projection_term(&mut self, projection: ty::AliasTerm<'tcx>) -> V::Result {
120        let tcx = self.def_id_visitor.tcx();
121        let (trait_ref, assoc_args) = projection.trait_ref_and_own_args(tcx);
122        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));
123        if V::SHALLOW {
124            V::Result::output()
125        } else {
126            V::Result::from_branch(
127                assoc_args.iter().try_for_each(|arg| arg.visit_with(self).branch()),
128            )
129        }
130    }
131
132    fn visit_clause(&mut self, clause: ty::Binder<'tcx, ty::ClauseKind<'tcx>>) -> V::Result {
133        match clause.skip_binder() {
134            ty::ClauseKind::Trait(ty::TraitClause { trait_ref, polarity: _ }) => {
135                self.visit_trait(trait_ref)
136            }
137            ty::ClauseKind::HostEffect(clause) => {
138                match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_trait(clause.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(clause.trait_ref));
139                clause.constness.visit_with(self)
140            }
141            ty::ClauseKind::Projection(ty::ProjectionClause {
142                projection_term: projection_ty,
143                term,
144            }) => {
145                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));
146                self.visit_projection_term(projection_ty)
147            }
148            ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ty, _region)) => ty.visit_with(self),
149            ty::ClauseKind::RegionOutlives(..) => V::Result::output(),
150            ty::ClauseKind::ConstArgHasType(ct, ty) => {
151                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));
152                ty.visit_with(self)
153            }
154            ty::ClauseKind::ConstEvaluatable(ct) => ct.visit_with(self),
155            ty::ClauseKind::WellFormed(term) => term.visit_with(self),
156            ty::ClauseKind::UnstableFeature(_) => V::Result::output(),
157        }
158    }
159
160    fn visit_clauses(&mut self, clauses: &[(ty::Clause<'tcx>, Span)]) -> V::Result {
161        for &(clause, _) in clauses {
162            match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_clause(clause.kind()))
    {
    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.kind()));
163        }
164        V::Result::output()
165    }
166}
167
168impl<'tcx, V> TypeVisitor<TyCtxt<'tcx>> for DefIdVisitorSkeleton<'_, 'tcx, V>
169where
170    V: DefIdVisitor<'tcx> + ?Sized,
171{
172    type Result = V::Result;
173
174    fn visit_predicate<P: PredicateProxy<TyCtxt<'tcx>>>(&mut self, p: P) -> Self::Result {
175        self.visit_clause(p.clause_kind_unchecked().unwrap())
176    }
177
178    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
179        let tcx = self.def_id_visitor.tcx();
180        // GenericArgs are not visited here because they are visited below
181        // in `super_visit_with`.
182        let ty_kind = *ty.kind();
183        match ty_kind {
184            ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), ..)
185            | ty::Foreign(def_id)
186            | ty::FnDef(def_id, ..)
187            | ty::Closure(def_id, ..)
188            | ty::CoroutineClosure(def_id, ..)
189            | ty::Coroutine(def_id, ..) => {
190                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));
191                if V::SHALLOW {
192                    return V::Result::output();
193                }
194                // Default type visitor doesn't visit signatures of fn types.
195                // Something like `fn() -> Priv {my_func}` is considered a private type even if
196                // `my_func` is public, so we need to visit signatures.
197                if let ty::FnDef(..) = ty_kind {
198                    // FIXME: this should probably use `args` from `FnDef`
199                    match ::rustc_ast_ir::visit::VisitorResult::branch(tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip().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!(
200                        tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip().visit_with(self)
201                    );
202                }
203                // Inherent static methods don't have self type in args.
204                // Something like `fn() {my_method}` type of the method
205                // `impl Pub<Priv> { pub fn my_method() {} }` is considered a private type,
206                // so we need to visit the self type additionally.
207                if let Some(assoc_item) = tcx.opt_associated_item(def_id)
208                    && let Some(impl_def_id) = assoc_item.impl_container(tcx)
209                {
210                    match ::rustc_ast_ir::visit::VisitorResult::branch(tcx.type_of(impl_def_id).instantiate_identity().skip_norm_wip().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!(
211                        tcx.type_of(impl_def_id)
212                            .instantiate_identity()
213                            .skip_norm_wip()
214                            .visit_with(self)
215                    );
216                }
217            }
218            ty::Alias(
219                _,
220                data @ ty::AliasTy {
221                    kind:
222                        kind @ (ty::Inherent { def_id }
223                        | ty::Free { def_id }
224                        | ty::Projection { def_id }),
225                    ..
226                },
227            ) => {
228                if self.def_id_visitor.skip_assoc_tys() {
229                    // Visitors searching for minimal visibility/reachability want to
230                    // conservatively approximate associated types like `Type::Alias`
231                    // as visible/reachable even if `Type` is private.
232                    // Ideally, associated types should be instantiated in the same way as
233                    // free type aliases, but this isn't done yet.
234                    return V::Result::output();
235                }
236                if !self.visited_tys.insert(ty) {
237                    // Avoid repeatedly visiting alias types (including projections).
238                    // This helps with special cases like #145741, but doesn't introduce
239                    // too much overhead in general case, unlike caching for other types.
240                    return V::Result::output();
241                }
242
243                match ::rustc_ast_ir::visit::VisitorResult::branch(self.def_id_visitor.visit_def_id(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, 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(
244                    def_id,
245                    match kind {
246                        ty::Inherent { .. } | ty::Projection { .. } => "associated type",
247                        ty::Free { .. } => "type alias",
248                        ty::Opaque { .. } => unreachable!(),
249                    },
250                    &LazyDefPathStr { def_id, tcx },
251                ));
252
253                // This will also visit args if necessary, so we don't need to recurse.
254                return if V::SHALLOW {
255                    V::Result::output()
256                } else if #[allow(non_exhaustive_omitted_patterns)] match kind {
    ty::Projection { .. } => true,
    _ => false,
}matches!(kind, ty::Projection { .. }) {
257                    self.visit_projection_term(data.into())
258                } else {
259                    V::Result::from_branch(
260                        data.args.iter().try_for_each(|arg| arg.visit_with(self).branch()),
261                    )
262                };
263            }
264            ty::Dynamic(predicates, ..) => {
265                // All traits in the list are considered the "primary" part of the type
266                // and are visited by shallow visitors.
267                for predicate in predicates {
268                    let trait_ref = match predicate.skip_binder() {
269                        ty::ExistentialPredicate::Trait(trait_ref) => trait_ref,
270                        ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx),
271                        ty::ExistentialPredicate::AutoTrait(def_id) => {
272                            ty::ExistentialTraitRef::new(tcx, def_id, ty::GenericArgs::empty())
273                        }
274                    };
275                    let ty::ExistentialTraitRef { def_id, .. } = trait_ref;
276                    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));
277                }
278            }
279            ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }) => {
280                // Skip repeated `Opaque`s to avoid infinite recursion.
281                if self.visited_tys.insert(ty) {
282                    // The intent is to treat `impl Trait1 + Trait2` identically to
283                    // `dyn Trait1 + Trait2`. Therefore we ignore def-id of the opaque type itself
284                    // (it either has no visibility, or its visibility is insignificant, like
285                    // visibilities of type aliases) and recurse into bounds instead to go
286                    // through the trait list (default type visitor doesn't visit those traits).
287                    // All traits in the list are considered the "primary" part of the type
288                    // and are visited by shallow visitors.
289                    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()));
290                }
291            }
292            // These types don't have their own def-ids (but may have subcomponents
293            // with def-ids that should be visited recursively).
294            ty::Bool
295            | ty::Char
296            | ty::Int(..)
297            | ty::Uint(..)
298            | ty::Float(..)
299            | ty::Str
300            | ty::Never
301            | ty::Array(..)
302            | ty::Slice(..)
303            | ty::Tuple(..)
304            | ty::RawPtr(..)
305            | ty::Ref(..)
306            | ty::Pat(..)
307            | ty::FnPtr(..)
308            | ty::UnsafeBinder(_)
309            | ty::Param(..)
310            | ty::Bound(..)
311            | ty::Error(_)
312            | ty::CoroutineWitness(..) => {}
313            ty::Placeholder(..) | ty::Infer(..) => {
314                ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected type: {0:?}", ty), Location::caller())bug!("unexpected type: {:?}", ty)
315            }
316        }
317
318        if V::SHALLOW { V::Result::output() } else { ty.super_visit_with(self) }
319    }
320
321    fn visit_const(&mut self, c: Const<'tcx>) -> Self::Result {
322        let tcx = self.def_id_visitor.tcx();
323        tcx.expand_abstract_consts(c).super_visit_with(self)
324    }
325}
326
327fn assoc_has_type_of(tcx: TyCtxt<'_>, item: &ty::AssocItem) -> bool {
328    if let ty::AssocKind::Type { data: ty::AssocTypeData::Normal(..) } = item.kind
329        && let hir::Node::TraitItem(item) =
330            tcx.hir_node(tcx.local_def_id_to_hir_id(item.def_id.expect_local()))
331        && let hir::TraitItemKind::Type(_, None) = item.kind
332    {
333        false
334    } else {
335        true
336    }
337}
338
339fn min(vis1: ty::Visibility, vis2: ty::Visibility, tcx: TyCtxt<'_>) -> ty::Visibility {
340    if vis1.greater_than(vis2, tcx) { vis2 } else { vis1 }
341}
342
343/// Visitor used to determine impl visibility and reachability.
344struct FindMin<'a, 'tcx, VL: VisibilityLike, const SHALLOW: bool> {
345    tcx: TyCtxt<'tcx>,
346    effective_visibilities: &'a EffectiveVisibilities,
347    min: VL,
348}
349
350impl<'a, 'tcx, VL: VisibilityLike, const SHALLOW: bool> DefIdVisitor<'tcx>
351    for FindMin<'a, 'tcx, VL, SHALLOW>
352{
353    const SHALLOW: bool = SHALLOW;
354    fn skip_assoc_tys(&self) -> bool {
355        true
356    }
357    fn tcx(&self) -> TyCtxt<'tcx> {
358        self.tcx
359    }
360    fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) {
361        if let Some(def_id) = def_id.as_local() {
362            self.min = VL::new_min(self, def_id);
363        }
364    }
365}
366
367trait VisibilityLike: Sized {
368    const MAX: Self;
369    fn new_min<const SHALLOW: bool>(
370        find: &FindMin<'_, '_, Self, SHALLOW>,
371        def_id: LocalDefId,
372    ) -> Self;
373
374    // Returns an over-approximation (`skip_assoc_tys()` = true) of visibility due to
375    // associated types for which we can't determine visibility precisely.
376    fn of_impl<const SHALLOW: bool>(
377        def_id: LocalDefId,
378        of_trait: bool,
379        tcx: TyCtxt<'_>,
380        effective_visibilities: &EffectiveVisibilities,
381    ) -> Self {
382        let mut find = FindMin::<_, SHALLOW> { tcx, effective_visibilities, min: Self::MAX };
383        find.visit(tcx.type_of(def_id).instantiate_identity().skip_norm_wip());
384        if of_trait {
385            find.visit_trait(tcx.impl_trait_ref(def_id).instantiate_identity().skip_norm_wip());
386        }
387        find.min
388    }
389}
390
391impl VisibilityLike for ty::Visibility {
392    const MAX: Self = ty::Visibility::Public;
393    fn new_min<const SHALLOW: bool>(
394        find: &FindMin<'_, '_, Self, SHALLOW>,
395        def_id: LocalDefId,
396    ) -> Self {
397        min(find.tcx.local_visibility(def_id), find.min, find.tcx)
398    }
399}
400
401impl VisibilityLike for EffectiveVisibility {
402    const MAX: Self = EffectiveVisibility::from_vis(ty::Visibility::Public);
403    fn new_min<const SHALLOW: bool>(
404        find: &FindMin<'_, '_, Self, SHALLOW>,
405        def_id: LocalDefId,
406    ) -> Self {
407        let effective_vis =
408            find.effective_visibilities.effective_vis(def_id).copied().unwrap_or_else(|| {
409                let private_vis =
410                    ty::Visibility::Restricted(find.tcx.parent_module_from_def_id(def_id));
411                EffectiveVisibility::from_vis(private_vis)
412            });
413
414        effective_vis.min(find.min, find.tcx)
415    }
416}
417
418type DefIdsToImpls = FxHashMap<LocalDefId, FxHashSet<LocalDefId>>;
419
420/// Visitor that collects correspondence map between defs and
421/// enclosing impls.
422struct DefIdsToImplsCollector<'tcx, 'a> {
423    tcx: TyCtxt<'tcx>,
424    def_ids_to_impls: &'a mut DefIdsToImpls,
425    impl_def_id: LocalDefId,
426}
427
428impl<'tcx, 'a> DefIdsToImplsCollector<'tcx, 'a> {
429    fn collect(tcx: TyCtxt<'tcx>) -> DefIdsToImpls {
430        let mut def_ids_to_impls = Default::default();
431        for item in tcx.hir_free_items() {
432            let impl_def_id = item.owner_id.def_id;
433            let DefKind::Impl { of_trait } = tcx.def_kind(impl_def_id) else {
434                continue;
435            };
436
437            // This behavior should mirror `EffectiveVisibility::of_impl::<true>`.
438            let mut visitor = DefIdsToImplsCollector {
439                tcx,
440                impl_def_id,
441                def_ids_to_impls: &mut def_ids_to_impls,
442            };
443
444            visitor.visit(tcx.type_of(impl_def_id).instantiate_identity().skip_norm_wip());
445            if of_trait {
446                visitor.visit_trait(
447                    tcx.impl_trait_ref(impl_def_id).instantiate_identity().skip_norm_wip(),
448                );
449            }
450        }
451
452        def_ids_to_impls
453    }
454}
455
456impl<'tcx, 'a> DefIdVisitor<'tcx> for DefIdsToImplsCollector<'tcx, 'a> {
457    const SHALLOW: bool = true;
458    fn skip_assoc_tys(&self) -> bool {
459        true
460    }
461    fn tcx(&self) -> TyCtxt<'tcx> {
462        self.tcx
463    }
464    fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) {
465        if let Some(def_id) = def_id.as_local() {
466            if true {
    {
        match self.tcx.def_kind(def_id) {
            DefKind::Enum | DefKind::Union | DefKind::Struct |
                DefKind::ForeignTy | DefKind::Trait => {}
            ref left_val => {
                ::core::panicking::assert_matches_failed(left_val,
                    "DefKind::Enum | DefKind::Union | DefKind::Struct | DefKind::ForeignTy |\nDefKind::Trait",
                    ::core::option::Option::None);
            }
        }
    };
};debug_assert_matches!(
467                self.tcx.def_kind(def_id),
468                DefKind::Enum
469                    | DefKind::Union
470                    | DefKind::Struct
471                    | DefKind::ForeignTy
472                    | DefKind::Trait
473            );
474            self.def_ids_to_impls.entry(def_id).or_default().insert(self.impl_def_id);
475        }
476    }
477}
478
479/// The embargo visitor, used to determine the exports of the AST.
480struct EmbargoVisitor<'tcx> {
481    tcx: TyCtxt<'tcx>,
482    /// Effective visibilities for reachable nodes.
483    effective_visibilities: EffectiveVisibilities,
484    /// Queue with modified items.
485    queue: IndexSet<LocalDefId>,
486    /// Correspondence between def and impls containing this def.
487    def_ids_to_impls: DefIdsToImpls,
488}
489
490struct ReachEverythingInTheInterfaceVisitor<'a, 'tcx> {
491    effective_vis: EffectiveVisibility,
492    item_def_id: LocalDefId,
493    ev: &'a mut EmbargoVisitor<'tcx>,
494    level: Level,
495}
496
497impl<'tcx> EmbargoVisitor<'tcx> {
498    fn get(&self, def_id: LocalDefId) -> Option<EffectiveVisibility> {
499        self.effective_visibilities.effective_vis(def_id).copied()
500    }
501
502    // Updates node effective visibility.
503    fn update(
504        &mut self,
505        def_id: LocalDefId,
506        inherited_effective_vis: EffectiveVisibility,
507        level: Level,
508    ) {
509        let nominal_vis = self.tcx.local_visibility(def_id);
510        self.update_eff_vis(def_id, inherited_effective_vis, Some(nominal_vis), level);
511    }
512
513    fn update_eff_vis(
514        &mut self,
515        def_id: LocalDefId,
516        inherited_effective_vis: EffectiveVisibility,
517        max_vis: Option<ty::Visibility>,
518        level: Level,
519    ) -> bool {
520        let private_vis =
521            ty::Visibility::Restricted(self.tcx.parent_module_from_def_id(def_id).into());
522        if max_vis != Some(private_vis) {
523            return self.effective_visibilities.update(
524                def_id,
525                max_vis,
526                private_vis,
527                inherited_effective_vis,
528                level,
529                self.tcx,
530            );
531        }
532        false
533    }
534
535    fn reach(
536        &mut self,
537        def_id: LocalDefId,
538        effective_vis: EffectiveVisibility,
539    ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
540        ReachEverythingInTheInterfaceVisitor {
541            effective_vis,
542            item_def_id: def_id,
543            ev: self,
544            level: Level::Reachable,
545        }
546    }
547
548    fn reach_through_impl_trait(
549        &mut self,
550        def_id: LocalDefId,
551        effective_vis: EffectiveVisibility,
552    ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
553        ReachEverythingInTheInterfaceVisitor {
554            effective_vis,
555            item_def_id: def_id,
556            ev: self,
557            level: Level::ReachableThroughImplTrait,
558        }
559    }
560}
561
562impl<'tcx> EmbargoVisitor<'tcx> {
563    fn check_assoc_item(&mut self, item: &ty::AssocItem, item_ev: EffectiveVisibility) {
564        let def_id = item.def_id.expect_local();
565        let tcx = self.tcx;
566        let mut reach = self.reach(def_id, item_ev);
567        reach.generics().clauses();
568        if assoc_has_type_of(tcx, item) {
569            reach.ty();
570        }
571        if item.is_type() && item.container == AssocContainer::Trait {
572            reach.bounds();
573        }
574    }
575
576    fn check_def_id(&mut self, def_id: LocalDefId) {
577        // Update levels of nested things and mark all items
578        // in interfaces of reachable items as reachable.
579        let item_ev = self.get(def_id);
580        let def_kind = self.tcx.def_kind(def_id);
581        match def_kind {
582            // The interface is empty, and no nested items.
583            DefKind::Use
584            | DefKind::ExternCrate
585            | DefKind::GlobalAsm
586            | DefKind::TestBinderConstraints => {}
587            // The interface is empty, and all nested items are processed by `check_def_id`.
588            DefKind::Mod => {}
589            // Effective visibilities for macros are processed earlier.
590            DefKind::Macro { .. } => {}
591            DefKind::ForeignTy
592            | DefKind::Const
593            | DefKind::Static { .. }
594            | DefKind::Fn
595            | DefKind::TyAlias => {
596                if let Some(item_ev) = item_ev {
597                    self.reach(def_id, item_ev).generics().clauses().ty();
598                }
599            }
600            DefKind::Trait => {
601                if let Some(item_ev) = item_ev {
602                    self.reach(def_id, item_ev).generics().clauses();
603
604                    for assoc_item in self.tcx.associated_items(def_id).in_definition_order() {
605                        let def_id = assoc_item.def_id.expect_local();
606                        self.update(def_id, item_ev, Level::Reachable);
607
608                        self.check_assoc_item(assoc_item, item_ev);
609                    }
610                }
611            }
612            DefKind::TraitAlias => {
613                if let Some(item_ev) = item_ev {
614                    self.reach(def_id, item_ev).generics().clauses();
615                }
616            }
617            DefKind::Impl { of_trait } => {
618                // Type inference is very smart sometimes. It can make an impl reachable even some
619                // components of its type or trait are unreachable. E.g. methods of
620                // `impl ReachableTrait<UnreachableTy> for ReachableTy<UnreachableTy> { ... }`
621                // can be usable from other crates (#57264). So we skip args when calculating
622                // reachability and consider an impl reachable if its "shallow" type and trait are
623                // reachable.
624                //
625                // The assumption we make here is that type-inference won't let you use an impl
626                // without knowing both "shallow" version of its self type and "shallow" version of
627                // its trait if it exists (which require reaching the `DefId`s in them).
628                let item_ev = EffectiveVisibility::of_impl::<true>(
629                    def_id,
630                    of_trait,
631                    self.tcx,
632                    &self.effective_visibilities,
633                );
634
635                self.update_eff_vis(def_id, item_ev, None, Level::Direct);
636
637                {
638                    let mut reach = self.reach(def_id, item_ev);
639                    reach.generics().clauses().ty();
640                    if of_trait {
641                        reach.trait_ref();
642                    }
643                }
644
645                for assoc_item in self.tcx.associated_items(def_id).in_definition_order() {
646                    let def_id = assoc_item.def_id.expect_local();
647                    let max_vis =
648                        if of_trait { None } else { Some(self.tcx.local_visibility(def_id)) };
649                    self.update_eff_vis(def_id, item_ev, max_vis, Level::Direct);
650
651                    if let Some(impl_item_ev) = self.get(def_id) {
652                        self.check_assoc_item(assoc_item, impl_item_ev);
653                    }
654                }
655            }
656            DefKind::Enum => {
657                if let Some(item_ev) = item_ev {
658                    self.reach(def_id, item_ev).generics().clauses();
659                }
660                let def = self.tcx.adt_def(def_id);
661                for variant in def.variants() {
662                    if let Some(item_ev) = item_ev {
663                        self.update(variant.def_id.expect_local(), item_ev, Level::Reachable);
664                    }
665
666                    if let Some(variant_ev) = self.get(variant.def_id.expect_local()) {
667                        if let Some(ctor_def_id) = variant.ctor_def_id() {
668                            self.update(ctor_def_id.expect_local(), variant_ev, Level::Reachable);
669                        }
670
671                        for field in &variant.fields {
672                            let field = field.did.expect_local();
673                            self.update(field, variant_ev, Level::Reachable);
674                            self.reach(field, variant_ev).ty();
675                        }
676                        // Corner case: if the variant is reachable, but its
677                        // enum is not, make the enum reachable as well.
678                        self.reach(def_id, variant_ev).ty();
679                    }
680                    if let Some(ctor_def_id) = variant.ctor_def_id() {
681                        if let Some(ctor_ev) = self.get(ctor_def_id.expect_local()) {
682                            self.reach(def_id, ctor_ev).ty();
683                        }
684                    }
685                }
686            }
687            DefKind::Struct | DefKind::Union => {
688                let def = self.tcx.adt_def(def_id).non_enum_variant();
689                if let Some(item_ev) = item_ev {
690                    self.reach(def_id, item_ev).generics().clauses();
691                    for field in &def.fields {
692                        let field = field.did.expect_local();
693                        self.update(field, item_ev, Level::Reachable);
694                        if let Some(field_ev) = self.get(field) {
695                            self.reach(field, field_ev).ty();
696                        }
697                    }
698                }
699                if let Some(ctor_def_id) = def.ctor_def_id() {
700                    if let Some(item_ev) = item_ev {
701                        self.update(ctor_def_id.expect_local(), item_ev, Level::Reachable);
702                    }
703                    if let Some(ctor_ev) = self.get(ctor_def_id.expect_local()) {
704                        self.reach(def_id, ctor_ev).ty();
705                    }
706                }
707            }
708            // Contents are checked directly.
709            DefKind::ForeignMod => {}
710            DefKind::Field
711            | DefKind::Variant
712            | DefKind::AssocFn
713            | DefKind::AssocTy
714            | DefKind::AssocConst
715            | DefKind::TyParam
716            | DefKind::AnonConst
717            | DefKind::OpaqueTy
718            | DefKind::Closure
719            | DefKind::SyntheticCoroutineBody
720            | DefKind::ConstParam
721            | DefKind::LifetimeParam
722            | DefKind::Ctor(..) => {
723                ::rustc_span::macros::bug_impl(Some(self.tcx.def_span(def_id)),
    format_args!("{0:?} should be checked while checking parent", def_kind),
    Location::caller())span_bug!(
724                    self.tcx.def_span(def_id),
725                    "{def_kind:?} should be checked while checking parent"
726                )
727            }
728        }
729    }
730}
731
732impl ReachEverythingInTheInterfaceVisitor<'_, '_> {
733    fn generics(&mut self) -> &mut Self {
734        for param in &self.ev.tcx.generics_of(self.item_def_id).own_params {
735            if let GenericParamDefKind::Const { .. } = param.kind {
736                self.visit(
737                    self.ev.tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip(),
738                );
739            }
740            if let Some(default) = param.default_value(self.ev.tcx) {
741                self.visit(default.instantiate_identity().skip_norm_wip());
742            }
743        }
744        self
745    }
746
747    fn clauses(&mut self) -> &mut Self {
748        self.visit_gen_clauses(self.ev.tcx.explicit_clauses_of(self.item_def_id));
749        self
750    }
751
752    fn bounds(&mut self) -> &mut Self {
753        self.visit_clauses(self.ev.tcx.explicit_item_bounds(self.item_def_id).skip_binder());
754        self
755    }
756
757    fn ty(&mut self) -> &mut Self {
758        self.visit(self.ev.tcx.type_of(self.item_def_id).instantiate_identity().skip_norm_wip());
759        self
760    }
761
762    fn trait_ref(&mut self) -> &mut Self {
763        self.visit_trait(
764            self.ev.tcx.impl_trait_ref(self.item_def_id).instantiate_identity().skip_norm_wip(),
765        );
766        self
767    }
768
769    // If a def encountered in the interface is updated, we put those items
770    // that may be affected by this update into the queue.
771    fn enqueue_def_id(&mut self, def_id: LocalDefId) {
772        let def_kind = self.ev.tcx.def_kind(def_id);
773        match def_kind {
774            DefKind::Enum
775            | DefKind::Union
776            | DefKind::Struct
777            | DefKind::ForeignTy
778            | DefKind::Trait => {
779                self.ev.queue.insert(def_id);
780                // Make sure that all affected impls are traversed one more time.
781                if let Some(impls) = self.ev.def_ids_to_impls.get(&def_id) {
782                    // The order in which items are traversed is irrelevant.
783                    #[allow(rustc::potential_query_instability)]
784                    self.ev.queue.extend(impls);
785                }
786            }
787
788            DefKind::TraitAlias | DefKind::Fn | DefKind::TyAlias => {
789                self.ev.queue.insert(def_id);
790            }
791
792            DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy => {
793                // Traverse the whole impl/trait.
794                self.ev.queue.insert(self.ev.tcx.local_parent(def_id));
795            }
796
797            DefKind::Ctor(ctor_of, _) => {
798                let update_id = match ctor_of {
799                    CtorOf::Struct => self.ev.tcx.local_parent(def_id),
800                    CtorOf::Variant => self.ev.tcx.local_parent(self.ev.tcx.local_parent(def_id)),
801                };
802                // Update the whole ADT.
803                self.ev.queue.insert(update_id);
804            }
805
806            // Can be reached via RPIT (impl Fn), but can't affect
807            // the effective visibility of other defs.
808            DefKind::Closure => {}
809
810            // Can't be reached
811            DefKind::Impl { .. }
812            | DefKind::Field
813            | DefKind::Variant
814            | DefKind::Static { .. }
815            | DefKind::Macro(_)
816            | DefKind::TyParam
817            | DefKind::AnonConst
818            | DefKind::OpaqueTy
819            | DefKind::SyntheticCoroutineBody
820            | DefKind::ConstParam
821            | DefKind::LifetimeParam
822            | DefKind::Mod
823            | DefKind::Use
824            | DefKind::ExternCrate
825            | DefKind::GlobalAsm
826            | DefKind::ForeignMod
827            | DefKind::Const
828            | DefKind::TestBinderConstraints => {
829                ::rustc_span::macros::bug_impl(Some(self.tcx().def_span(def_id)),
    format_args!("{0:?} unexpectedly reached by `ReachEverythingInTheInterfaceVisitor`",
        def_kind), Location::caller())span_bug!(
830                    self.tcx().def_span(def_id),
831                    "{def_kind:?} unexpectedly reached by `ReachEverythingInTheInterfaceVisitor`"
832                )
833            }
834        }
835    }
836}
837
838impl<'tcx> DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
839    fn tcx(&self) -> TyCtxt<'tcx> {
840        self.ev.tcx
841    }
842    fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) {
843        if let Some(def_id) = def_id.as_local() {
844            // All effective visibilities except `reachable_through_impl_trait` are limited to
845            // nominal visibility. If any type or trait is leaked farther than that, it will
846            // produce type privacy errors on any use, so we don't consider it leaked.
847            //
848            // FIXME: If self.level == Level::Reachable and self.ev == (priv, priv, priv, pub),
849            // then the effective visibility of def_id wouldn't be updated at level
850            // `ReachableThroughImplTrait` due to max_vis. Could this lead to a privacy violation?
851            let max_vis = (self.level != Level::ReachableThroughImplTrait)
852                .then(|| self.ev.tcx.local_visibility(def_id));
853            if self.ev.update_eff_vis(def_id, self.effective_vis, max_vis, self.level) {
854                self.enqueue_def_id(def_id);
855            }
856        }
857    }
858}
859
860/// Visitor, used for EffectiveVisibilities table checking
861pub struct TestReachabilityVisitor<'a, 'tcx> {
862    tcx: TyCtxt<'tcx>,
863    effective_visibilities: &'a EffectiveVisibilities,
864}
865
866impl<'a, 'tcx> TestReachabilityVisitor<'a, 'tcx> {
867    fn effective_visibility_diagnostic(&self, def_id: LocalDefId) {
868        if {
        {
            'done:
                {
                for i in
                    ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &self.tcx) {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(RustcEffectiveVisibility)
                            => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(self.tcx, def_id, RustcEffectiveVisibility) {
869            let mut error_msg = String::new();
870            let span = self.tcx.def_span(def_id.to_def_id());
871            if let Some(effective_vis) = self.effective_visibilities.effective_vis(def_id) {
872                for level in Level::all_levels() {
873                    let vis_str = effective_vis.at_level(level).to_string(def_id, self.tcx);
874                    if level != Level::Direct {
875                        error_msg.push_str(", ");
876                    }
877                    error_msg.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}: {1}", level, vis_str))
    })format!("{level:?}: {vis_str}"));
878                }
879            } else {
880                error_msg.push_str("not in the table");
881            }
882            self.tcx.dcx().emit_err(ReportEffectiveVisibility { span, descr: error_msg });
883        }
884    }
885}
886
887impl<'a, 'tcx> TestReachabilityVisitor<'a, 'tcx> {
888    fn check_def_id(&self, owner_id: OwnerId) {
889        self.effective_visibility_diagnostic(owner_id.def_id);
890
891        match self.tcx.def_kind(owner_id) {
892            DefKind::Enum => {
893                let def = self.tcx.adt_def(owner_id.def_id);
894                for variant in def.variants() {
895                    self.effective_visibility_diagnostic(variant.def_id.expect_local());
896                    if let Some(ctor_def_id) = variant.ctor_def_id() {
897                        self.effective_visibility_diagnostic(ctor_def_id.expect_local());
898                    }
899                    for field in &variant.fields {
900                        self.effective_visibility_diagnostic(field.did.expect_local());
901                    }
902                }
903            }
904            DefKind::Struct | DefKind::Union => {
905                let def = self.tcx.adt_def(owner_id.def_id).non_enum_variant();
906                if let Some(ctor_def_id) = def.ctor_def_id() {
907                    self.effective_visibility_diagnostic(ctor_def_id.expect_local());
908                }
909                for field in &def.fields {
910                    self.effective_visibility_diagnostic(field.did.expect_local());
911                }
912            }
913            _ => {}
914        }
915    }
916}
917
918/// Name privacy visitor, checks privacy and reports violations.
919///
920/// Most of name privacy checks are performed during the main resolution phase,
921/// or later in type checking when field accesses and associated items are resolved.
922/// This pass performs remaining checks for fields in struct expressions and patterns.
923struct NamePrivacyVisitor<'tcx> {
924    tcx: TyCtxt<'tcx>,
925    mod_id: LocalModId,
926    maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
927}
928
929impl<'tcx> NamePrivacyVisitor<'tcx> {
930    /// Gets the type-checking results for the current body.
931    /// As this will ICE if called outside bodies, only call when working with
932    /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
933    #[track_caller]
934    fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
935        self.maybe_typeck_results
936            .expect("`NamePrivacyVisitor::typeck_results` called outside of body")
937    }
938
939    // Checks that a field in a struct constructor (expression or pattern) is accessible.
940    fn check_field(
941        &self,
942        use_ctxt: Span,        // syntax context of the field name at the use site
943        def: ty::AdtDef<'tcx>, // definition of the struct or enum
944        field: &'tcx ty::FieldDef,
945    ) -> bool {
946        if def.is_enum() {
947            return true;
948        }
949
950        // definition of the field
951        let ident = Ident::new(sym::dummy, use_ctxt);
952        let (_, def_id) = self.tcx.adjust_ident_and_get_scope(ident, def.did(), self.mod_id);
953        !field.vis.is_accessible_from(def_id, self.tcx)
954    }
955
956    // Checks that a field in a struct constructor (expression or pattern) is accessible.
957    fn emit_unreachable_field_error(
958        &self,
959        fields: Vec<(Symbol, Span, bool /* field is present */)>,
960        def: ty::AdtDef<'tcx>, // definition of the struct or enum
961        update_syntax: Option<Span>,
962        struct_span: Span,
963    ) {
964        if def.is_enum() || fields.is_empty() {
965            return;
966        }
967
968        //   error[E0451]: fields `beta` and `gamma` of struct `Alpha` are private
969        //   --> $DIR/visibility.rs:18:13
970        //    |
971        // LL |     let _x = Alpha {
972        //    |              ----- in this type      # from `def`
973        // LL |         beta: 0,
974        //    |         ^^^^^^^ private field        # `fields.2` is `true`
975        // LL |         ..
976        //    |         ^^ field `gamma` is private  # `fields.2` is `false`
977
978        // Get the list of all private fields for the main message.
979        let Some(field_names) = listify(&fields[..], |(n, _, _)| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", n))
    })format!("`{n}`")) else { return };
980        let span: MultiSpan = fields.iter().map(|(_, span, _)| *span).collect::<Vec<Span>>().into();
981
982        // Get the list of all private fields when pointing at the `..rest`.
983        let rest_field_names: Vec<_> =
984            fields.iter().filter(|(_, _, is_present)| !is_present).map(|(n, _, _)| n).collect();
985        let rest_len = rest_field_names.len();
986        let rest_field_names =
987            listify(&rest_field_names[..], |n| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", n))
    })format!("`{n}`")).unwrap_or_default();
988        // Get all the labels for each field or `..rest` in the primary MultiSpan.
989        let labels = fields
990            .iter()
991            .filter(|(_, _, is_present)| *is_present)
992            .map(|(_, span, _)| FieldIsPrivateLabel::Other { span: *span })
993            .chain(update_syntax.iter().map(|span| FieldIsPrivateLabel::IsUpdateSyntax {
994                span: *span,
995                rest_field_names: rest_field_names.clone(),
996                rest_len,
997            }))
998            .collect();
999
1000        self.tcx.dcx().emit_err(FieldIsPrivate {
1001            span,
1002            struct_span: if self
1003                .tcx
1004                .sess
1005                .source_map()
1006                .is_multiline(fields[0].1.between(struct_span))
1007            {
1008                Some(struct_span)
1009            } else {
1010                None
1011            },
1012            field_names,
1013            variant_descr: def.variant_descr(),
1014            def_path_str: self.tcx.def_path_str(def.did()),
1015            labels,
1016            len: fields.len(),
1017        });
1018    }
1019
1020    fn check_expanded_fields(
1021        &self,
1022        adt: ty::AdtDef<'tcx>,
1023        variant: &'tcx ty::VariantDef,
1024        fields: &[hir::ExprField<'tcx>],
1025        span: Span,
1026        struct_span: Span,
1027    ) {
1028        let mut failed_fields = ::alloc::vec::Vec::new()vec![];
1029        for (vf_index, variant_field) in variant.fields.iter_enumerated() {
1030            let field =
1031                fields.iter().find(|f| self.typeck_results().field_index(f.hir_id) == vf_index);
1032            let (use_ctxt, span) = match field {
1033                Some(field) => (field.ident.span, field.span),
1034                None => (span, span),
1035            };
1036            if self.check_field(use_ctxt, adt, variant_field) {
1037                let name = match field {
1038                    Some(field) => field.ident.name,
1039                    None => variant_field.name,
1040                };
1041                failed_fields.push((name, span, field.is_some()));
1042            }
1043        }
1044        self.emit_unreachable_field_error(failed_fields, adt, Some(span), struct_span);
1045    }
1046}
1047
1048impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> {
1049    fn visit_nested_body(&mut self, body_id: hir::BodyId) {
1050        let new_typeck_results = self.tcx.typeck_body(body_id);
1051        // Do not try reporting privacy violations if we failed to infer types.
1052        if new_typeck_results.tainted_by_errors.is_some() {
1053            return;
1054        }
1055        let old_maybe_typeck_results = self.maybe_typeck_results.replace(new_typeck_results);
1056        self.visit_body(self.tcx.hir_body(body_id));
1057        self.maybe_typeck_results = old_maybe_typeck_results;
1058    }
1059
1060    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1061        if let hir::ExprKind::Struct(qpath, fields, ref base) = expr.kind {
1062            let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
1063            let adt = self.typeck_results().expr_ty(expr).ty_adt_def().unwrap();
1064            let variant = adt.variant_of_res(res);
1065            match *base {
1066                hir::StructTailExpr::Base(base) => {
1067                    // If the expression uses FRU we need to make sure all the unmentioned fields
1068                    // are checked for privacy (RFC 736). Rather than computing the set of
1069                    // unmentioned fields, just check them all.
1070                    self.check_expanded_fields(adt, variant, fields, base.span, qpath.span());
1071                }
1072                hir::StructTailExpr::DefaultFields(span) => {
1073                    self.check_expanded_fields(adt, variant, fields, span, qpath.span());
1074                }
1075                hir::StructTailExpr::None | hir::StructTailExpr::NoneWithError(_) => {
1076                    let mut failed_fields = ::alloc::vec::Vec::new()vec![];
1077                    for field in fields {
1078                        let index = self.typeck_results().field_index(field.hir_id);
1079                        if self.check_field(field.ident.span, adt, &variant.fields[index]) {
1080                            failed_fields.push((field.ident.name, field.ident.span, true));
1081                        }
1082                    }
1083                    self.emit_unreachable_field_error(failed_fields, adt, None, qpath.span());
1084                }
1085            }
1086        }
1087
1088        intravisit::walk_expr(self, expr);
1089    }
1090
1091    fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
1092        if let PatKind::Struct(ref qpath, fields, _) = pat.kind {
1093            let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
1094            let adt = self.typeck_results().pat_ty(pat).ty_adt_def().unwrap();
1095            let variant = adt.variant_of_res(res);
1096            let mut failed_fields = ::alloc::vec::Vec::new()vec![];
1097            for field in fields {
1098                let index = self.typeck_results().field_index(field.hir_id);
1099                if self.check_field(field.ident.span, adt, &variant.fields[index]) {
1100                    failed_fields.push((field.ident.name, field.ident.span, true));
1101                }
1102            }
1103            self.emit_unreachable_field_error(failed_fields, adt, None, qpath.span());
1104        }
1105
1106        intravisit::walk_pat(self, pat);
1107    }
1108}
1109
1110/// Type privacy visitor, checks types for privacy and reports violations.
1111///
1112/// Both explicitly written types and inferred types of expressions and patterns are checked.
1113/// Checks are performed on "semantic" types regardless of names and their hygiene.
1114struct TypePrivacyVisitor<'tcx> {
1115    tcx: TyCtxt<'tcx>,
1116    mod_id: LocalModId,
1117    maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
1118    span: Span,
1119    /// Types already walked clean (no privacy error). A walk's result depends only on the
1120    /// interned type and `mod_id`, which is fixed for the whole visit, so a type that walks
1121    /// clean once walks clean everywhere and we can skip it. Errored walks are never cached,
1122    /// so their error still fires at every span.
1123    accessible_tys: FxHashSet<Ty<'tcx>>,
1124}
1125
1126impl<'tcx> TypePrivacyVisitor<'tcx> {
1127    fn item_is_accessible(&self, did: DefId) -> bool {
1128        self.tcx.visibility(did).is_accessible_from(self.mod_id, self.tcx)
1129    }
1130
1131    fn check_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<()> {
1132        if self.accessible_tys.contains(&ty) {
1133            return ControlFlow::Continue(());
1134        }
1135        self.visit(ty)?;
1136        self.accessible_tys.insert(ty);
1137        ControlFlow::Continue(())
1138    }
1139
1140    // Take node-id of an expression or pattern and check its type for privacy.
1141    fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
1142        self.span = span;
1143        let typeck_results = self
1144            .maybe_typeck_results
1145            .unwrap_or_else(|| ::rustc_span::macros::bug_impl(Some(span),
    format_args!("`hir::Expr` or `hir::Pat` outside of a body"),
    Location::caller())span_bug!(span, "`hir::Expr` or `hir::Pat` outside of a body"));
1146        try {
1147            self.check_ty(typeck_results.node_type(id))?;
1148            self.visit(typeck_results.node_args(id))?;
1149            if let Some(adjustments) = typeck_results.adjustments().get(id) {
1150                adjustments.iter().try_for_each(|adjustment| self.check_ty(adjustment.target))?;
1151            }
1152        }
1153        .is_break()
1154    }
1155
1156    fn check_def_id(&self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1157        let is_error = !self.item_is_accessible(def_id);
1158        if is_error {
1159            self.tcx.dcx().emit_err(ItemIsPrivate { span: self.span, kind, descr: descr.into() });
1160        }
1161        is_error
1162    }
1163}
1164
1165impl<'tcx> rustc_ty_walk::SpannedTypeVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1166    type Result = ControlFlow<()>;
1167    fn visit(&mut self, span: Span, value: impl TypeVisitable<TyCtxt<'tcx>>) -> Self::Result {
1168        self.span = span;
1169        value.visit_with(&mut self.skeleton())
1170    }
1171}
1172
1173impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> {
1174    fn visit_nested_body(&mut self, body_id: hir::BodyId) {
1175        let old_maybe_typeck_results =
1176            self.maybe_typeck_results.replace(self.tcx.typeck_body(body_id));
1177        self.visit_body(self.tcx.hir_body(body_id));
1178        self.maybe_typeck_results = old_maybe_typeck_results;
1179    }
1180
1181    fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx, AmbigArg>) {
1182        self.span = hir_ty.span;
1183        let ty = self
1184            .maybe_typeck_results
1185            .unwrap_or_else(|| ::rustc_span::macros::bug_impl(Some(hir_ty.span),
    format_args!("`hir::Ty` outside of a body"), Location::caller())span_bug!(hir_ty.span, "`hir::Ty` outside of a body"))
1186            .node_type(hir_ty.hir_id);
1187        if self.check_ty(ty).is_break() {
1188            return;
1189        }
1190
1191        intravisit::walk_ty(self, hir_ty);
1192    }
1193
1194    fn visit_infer(
1195        &mut self,
1196        inf_id: rustc_hir::HirId,
1197        inf_span: Span,
1198        _kind: InferKind<'tcx>,
1199    ) -> Self::Result {
1200        self.span = inf_span;
1201        if let Some(ty) = self
1202            .maybe_typeck_results
1203            .unwrap_or_else(|| ::rustc_span::macros::bug_impl(Some(inf_span),
    format_args!("Inference variable outside of a body"), Location::caller())span_bug!(inf_span, "Inference variable outside of a body"))
1204            .node_type_opt(inf_id)
1205        {
1206            if self.check_ty(ty).is_break() {
1207                return;
1208            }
1209        } else {
1210            // FIXME: check types of const infers here.
1211        }
1212
1213        self.visit_id(inf_id)
1214    }
1215
1216    // Check types of expressions
1217    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1218        if self.check_expr_pat_type(expr.hir_id, expr.span) {
1219            // Do not check nested expressions if the error already happened.
1220            return;
1221        }
1222        match expr.kind {
1223            hir::ExprKind::Assign(_, rhs, _) | hir::ExprKind::Match(rhs, ..) => {
1224                // Do not report duplicate errors for `x = y` and `match x { ... }`.
1225                if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
1226                    return;
1227                }
1228            }
1229            hir::ExprKind::MethodCall(segment, ..) => {
1230                // Method calls have to be checked specially.
1231                self.span = segment.ident.span;
1232                let typeck_results = self
1233                    .maybe_typeck_results
1234                    .unwrap_or_else(|| ::rustc_span::macros::bug_impl(Some(self.span),
    format_args!("`hir::Expr` outside of a body"), Location::caller())span_bug!(self.span, "`hir::Expr` outside of a body"));
1235                if let Some(def_id) = typeck_results.type_dependent_def_id(expr.hir_id) {
1236                    if self
1237                        .check_ty(self.tcx.type_of(def_id).instantiate_identity().skip_norm_wip())
1238                        .is_break()
1239                    {
1240                        return;
1241                    }
1242                } else {
1243                    self.tcx
1244                        .dcx()
1245                        .span_delayed_bug(expr.span, "no type-dependent def for method call");
1246                }
1247            }
1248            _ => {}
1249        }
1250
1251        intravisit::walk_expr(self, expr);
1252    }
1253
1254    // Prohibit access to associated items with insufficient nominal visibility.
1255    //
1256    // Additionally, until better reachability analysis for macros 2.0 is available,
1257    // we prohibit access to private statics from other crates, this allows to give
1258    // more code internal visibility at link time. (Access to private functions
1259    // is already prohibited by type privacy for function types.)
1260    fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) {
1261        let def = match qpath {
1262            hir::QPath::Resolved(_, path) => match path.res {
1263                Res::Def(kind, def_id) => Some((kind, def_id)),
1264                _ => None,
1265            },
1266            hir::QPath::TypeRelative(..) => {
1267                match self.maybe_typeck_results {
1268                    Some(typeck_results) => typeck_results.type_dependent_def(id),
1269                    // FIXME: Check type-relative associated types in signatures.
1270                    None => None,
1271                }
1272            }
1273        };
1274        let def = def.filter(|(kind, _)| {
1275            #[allow(non_exhaustive_omitted_patterns)] match kind {
    DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy |
        DefKind::Static { .. } => true,
    _ => false,
}matches!(
1276                kind,
1277                DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static { .. }
1278            )
1279        });
1280        if let Some((kind, def_id)) = def {
1281            let is_local_static =
1282                if let DefKind::Static { .. } = kind { def_id.is_local() } else { false };
1283            if !self.item_is_accessible(def_id) && !is_local_static {
1284                let name = match *qpath {
1285                    hir::QPath::Resolved(_, path) => Some(self.tcx.def_path_str(path.res.def_id())),
1286                    hir::QPath::TypeRelative(_, segment) => Some(segment.ident.to_string()),
1287                };
1288                let kind = self.tcx.def_descr(def_id);
1289                let sess = self.tcx.sess;
1290                let _ = match name {
1291                    Some(name) => {
1292                        sess.dcx().emit_err(ItemIsPrivate { span, kind, descr: (&name).into() })
1293                    }
1294                    None => sess.dcx().emit_err(UnnamedItemIsPrivate { span, kind }),
1295                };
1296                return;
1297            }
1298        }
1299
1300        intravisit::walk_qpath(self, qpath, id);
1301    }
1302
1303    // Check types of patterns.
1304    fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) {
1305        if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
1306            // Do not check nested patterns if the error already happened.
1307            return;
1308        }
1309
1310        intravisit::walk_pat(self, pattern);
1311    }
1312
1313    fn visit_local(&mut self, local: &'tcx hir::LetStmt<'tcx>) {
1314        if let Some(init) = local.init {
1315            if self.check_expr_pat_type(init.hir_id, init.span) {
1316                // Do not report duplicate errors for `let x = y`.
1317                return;
1318            }
1319        }
1320
1321        intravisit::walk_local(self, local);
1322    }
1323}
1324
1325impl<'tcx> DefIdVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1326    type Result = ControlFlow<()>;
1327    fn tcx(&self) -> TyCtxt<'tcx> {
1328        self.tcx
1329    }
1330    fn visit_def_id(
1331        &mut self,
1332        def_id: DefId,
1333        kind: &str,
1334        descr: &dyn fmt::Display,
1335    ) -> Self::Result {
1336        if self.check_def_id(def_id, kind, descr) {
1337            ControlFlow::Break(())
1338        } else {
1339            ControlFlow::Continue(())
1340        }
1341    }
1342}
1343
1344/// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1345/// finds any private components in it.
1346///
1347/// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1348/// and traits in public interfaces.
1349struct SearchInterfaceForPrivateItemsVisitor<'tcx> {
1350    tcx: TyCtxt<'tcx>,
1351    item_def_id: LocalDefId,
1352    /// The visitor checks that each component type is at least this visible.
1353    required_visibility: ty::Visibility,
1354    required_effective_vis: Option<EffectiveVisibility>,
1355    hard_error: bool = false,
1356    in_primary_interface: bool = true,
1357    skip_assoc_tys: bool = false,
1358}
1359
1360impl SearchInterfaceForPrivateItemsVisitor<'_> {
1361    fn generics(&mut self) -> &mut Self {
1362        self.in_primary_interface = true;
1363        for param in &self.tcx.generics_of(self.item_def_id).own_params {
1364            if let GenericParamDefKind::Const { .. } = param.kind {
1365                let _ = self
1366                    .visit(self.tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip());
1367            }
1368            if let Some(default) = param.default_value(self.tcx) {
1369                let _ = self.visit(default.instantiate_identity().skip_norm_wip());
1370            }
1371        }
1372        self
1373    }
1374
1375    fn clauses(&mut self) -> &mut Self {
1376        self.in_primary_interface = false;
1377        // N.B., we use `explicit_clauses_of` and not `clauses_of`
1378        // because we don't want to report privacy errors due to where
1379        // clauses that the compiler inferred. We only want to
1380        // consider the ones that the user wrote. This is important
1381        // for the inferred outlives rules; see
1382        // `tests/ui/rfc-2093-infer-outlives/privacy.rs`.
1383        let _ = self.visit_gen_clauses(self.tcx.explicit_clauses_of(self.item_def_id));
1384        self
1385    }
1386
1387    fn bounds(&mut self) -> &mut Self {
1388        self.in_primary_interface = false;
1389        let _ = self.visit_clauses(self.tcx.explicit_item_bounds(self.item_def_id).skip_binder());
1390        self
1391    }
1392
1393    fn ty(&mut self) -> &mut Self {
1394        self.in_primary_interface = true;
1395        let _ =
1396            self.visit(self.tcx.type_of(self.item_def_id).instantiate_identity().skip_norm_wip());
1397        self
1398    }
1399
1400    fn trait_ref(&mut self) -> &mut Self {
1401        self.in_primary_interface = true;
1402        let _ = self.visit_trait(
1403            self.tcx.impl_trait_ref(self.item_def_id).instantiate_identity().skip_norm_wip(),
1404        );
1405        self
1406    }
1407
1408    fn check_def_id(&self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1409        if self.leaks_private_dep(def_id) {
1410            self.tcx.emit_node_span_lint(
1411                EXPORTED_PRIVATE_DEPENDENCIES,
1412                self.tcx.local_def_id_to_hir_id(self.item_def_id),
1413                self.tcx.def_span(self.item_def_id.to_def_id()),
1414                FromPrivateDependencyInPublicInterface {
1415                    kind,
1416                    descr: descr.into(),
1417                    krate: self.tcx.crate_name(def_id.krate),
1418                },
1419            );
1420        }
1421
1422        let Some(local_def_id) = def_id.as_local() else {
1423            return false;
1424        };
1425
1426        let vis = self.tcx.local_visibility(local_def_id);
1427        if self.hard_error && self.required_visibility.greater_than(vis, self.tcx) {
1428            let vis_descr = match vis {
1429                ty::Visibility::Public => "public",
1430                ty::Visibility::Restricted(vis_mod_id) => {
1431                    if vis_mod_id == self.tcx.parent_module_from_def_id(local_def_id) {
1432                        "private"
1433                    } else if vis_mod_id.is_top_level_module() {
1434                        "crate-private"
1435                    } else {
1436                        "restricted"
1437                    }
1438                }
1439            };
1440
1441            let span = self.tcx.def_span(self.item_def_id.to_def_id());
1442            let vis_span = self.tcx.def_span(def_id);
1443            self.tcx.dcx().emit_err(InPublicInterface {
1444                span,
1445                vis_descr,
1446                kind,
1447                descr: descr.into(),
1448                vis_span,
1449            });
1450            return false;
1451        }
1452
1453        let Some(effective_vis) = self.required_effective_vis else {
1454            return false;
1455        };
1456
1457        let reachable_at_vis = *effective_vis.at_level(Level::Reachable);
1458
1459        if reachable_at_vis.greater_than(vis, self.tcx) {
1460            let lint = if self.in_primary_interface { PRIVATE_INTERFACES } else { PRIVATE_BOUNDS };
1461            let span = self.tcx.def_span(self.item_def_id.to_def_id());
1462            let vis_span = self.tcx.def_span(def_id);
1463            self.tcx.emit_node_span_lint(
1464                lint,
1465                self.tcx.local_def_id_to_hir_id(self.item_def_id),
1466                span,
1467                PrivateInterfacesOrBoundsLint {
1468                    item_span: span,
1469                    item_kind: self.tcx.def_descr(self.item_def_id.to_def_id()),
1470                    item_descr: (&LazyDefPathStr {
1471                        def_id: self.item_def_id.to_def_id(),
1472                        tcx: self.tcx,
1473                    })
1474                        .into(),
1475                    item_vis_descr: &reachable_at_vis.to_string(self.item_def_id, self.tcx),
1476                    ty_span: vis_span,
1477                    ty_kind: kind,
1478                    ty_descr: descr.into(),
1479                    ty_vis_descr: &vis.to_string(local_def_id, self.tcx),
1480                },
1481            );
1482        }
1483
1484        false
1485    }
1486
1487    /// An item is 'leaked' from a private dependency if all
1488    /// of the following are true:
1489    /// 1. It's contained within a public type
1490    /// 2. It comes from a private crate
1491    fn leaks_private_dep(&self, item_id: DefId) -> bool {
1492        let ret = self.required_visibility.is_public() && self.tcx.is_private_dep(item_id.krate);
1493
1494        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_privacy/src/lib.rs:1494",
                        "rustc_privacy", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_privacy/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1494u32),
                        ::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};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("leaks_private_dep(item_id={0:?})={1}",
                                                    item_id, ret) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("leaks_private_dep(item_id={:?})={}", item_id, ret);
1495        ret
1496    }
1497}
1498
1499impl<'tcx> DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> {
1500    type Result = ControlFlow<()>;
1501    fn skip_assoc_tys(&self) -> bool {
1502        self.skip_assoc_tys
1503    }
1504    fn tcx(&self) -> TyCtxt<'tcx> {
1505        self.tcx
1506    }
1507    fn visit_def_id(
1508        &mut self,
1509        def_id: DefId,
1510        kind: &str,
1511        descr: &dyn fmt::Display,
1512    ) -> Self::Result {
1513        if self.check_def_id(def_id, kind, descr) {
1514            ControlFlow::Break(())
1515        } else {
1516            ControlFlow::Continue(())
1517        }
1518    }
1519}
1520
1521struct PrivateItemsInPublicInterfacesChecker<'a, 'tcx> {
1522    tcx: TyCtxt<'tcx>,
1523    effective_visibilities: &'a EffectiveVisibilities,
1524}
1525
1526impl<'tcx> PrivateItemsInPublicInterfacesChecker<'_, 'tcx> {
1527    fn check(
1528        &self,
1529        def_id: LocalDefId,
1530        required_visibility: ty::Visibility,
1531        required_effective_vis: Option<EffectiveVisibility>,
1532    ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> {
1533        SearchInterfaceForPrivateItemsVisitor {
1534            tcx: self.tcx,
1535            item_def_id: def_id,
1536            required_visibility,
1537            required_effective_vis,
1538            ..
1539        }
1540    }
1541
1542    fn check_unnameable(&self, def_id: LocalDefId, effective_vis: Option<EffectiveVisibility>) {
1543        let Some(effective_vis) = effective_vis else {
1544            return;
1545        };
1546
1547        let reexported_at_vis = effective_vis.at_level(Level::Reexported);
1548        let reachable_at_vis = effective_vis.at_level(Level::Reachable);
1549
1550        if reachable_at_vis.is_public() && reexported_at_vis != reachable_at_vis {
1551            let hir_id = self.tcx.local_def_id_to_hir_id(def_id);
1552            let span = self.tcx.def_span(def_id.to_def_id());
1553            self.tcx.emit_node_span_lint(
1554                UNNAMEABLE_TYPES,
1555                hir_id,
1556                span,
1557                UnnameableTypesLint {
1558                    span,
1559                    kind: self.tcx.def_descr(def_id.to_def_id()),
1560                    descr: (&LazyDefPathStr { def_id: def_id.to_def_id(), tcx: self.tcx }).into(),
1561                    reachable_vis: &reachable_at_vis.to_string(def_id, self.tcx),
1562                    reexported_vis: &reexported_at_vis.to_string(def_id, self.tcx),
1563                },
1564            );
1565        }
1566    }
1567
1568    fn check_assoc_item(
1569        &self,
1570        item: &ty::AssocItem,
1571        vis: ty::Visibility,
1572        effective_vis: Option<EffectiveVisibility>,
1573    ) {
1574        let mut check = self.check(item.def_id.expect_local(), vis, effective_vis);
1575
1576        let is_assoc_ty = item.is_type();
1577        check.hard_error = is_assoc_ty;
1578        check.generics().clauses();
1579        if assoc_has_type_of(self.tcx, item) {
1580            check.ty();
1581        }
1582        if is_assoc_ty && item.container == AssocContainer::Trait {
1583            // FIXME: too much breakage from reporting hard errors here, better wait for a fix
1584            // from proper associated type normalization.
1585            check.hard_error = false;
1586            check.bounds();
1587        }
1588    }
1589
1590    fn get(&self, def_id: LocalDefId) -> Option<EffectiveVisibility> {
1591        self.effective_visibilities.effective_vis(def_id).copied()
1592    }
1593
1594    fn check_item(&self, id: ItemId) {
1595        let tcx = self.tcx;
1596        let def_id = id.owner_id.def_id;
1597        let item_visibility = tcx.local_visibility(def_id);
1598        let effective_vis = self.get(def_id);
1599        let def_kind = tcx.def_kind(def_id);
1600
1601        match def_kind {
1602            DefKind::Const | DefKind::Static { .. } | DefKind::Fn | DefKind::TyAlias => {
1603                if let DefKind::TyAlias = def_kind {
1604                    self.check_unnameable(def_id, effective_vis);
1605                }
1606                self.check(def_id, item_visibility, effective_vis).generics().clauses().ty();
1607            }
1608            DefKind::OpaqueTy => {
1609                // `ty()` for opaque types is the underlying type,
1610                // it's not a part of interface, so we skip it.
1611                self.check(def_id, item_visibility, effective_vis).generics().bounds();
1612            }
1613            DefKind::Trait => {
1614                self.check_unnameable(def_id, effective_vis);
1615
1616                self.check(def_id, item_visibility, effective_vis).generics().clauses();
1617
1618                for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() {
1619                    self.check_assoc_item(assoc_item, item_visibility, effective_vis);
1620                }
1621            }
1622            DefKind::TraitAlias => {
1623                self.check(def_id, item_visibility, effective_vis).generics().clauses();
1624            }
1625            DefKind::Enum => {
1626                self.check_unnameable(def_id, effective_vis);
1627                self.check(def_id, item_visibility, effective_vis).generics().clauses();
1628
1629                let adt = tcx.adt_def(id.owner_id);
1630                for field in adt.all_fields() {
1631                    self.check(field.did.expect_local(), item_visibility, effective_vis).ty();
1632                }
1633            }
1634            // Subitems of structs and unions have their own publicity.
1635            DefKind::Struct | DefKind::Union => {
1636                self.check_unnameable(def_id, effective_vis);
1637                self.check(def_id, item_visibility, effective_vis).generics().clauses();
1638
1639                let adt = tcx.adt_def(id.owner_id);
1640                for field in adt.all_fields() {
1641                    let visibility = min(item_visibility, field.vis.expect_local(), tcx);
1642                    let field_ev = self.get(field.did.expect_local());
1643
1644                    self.check(field.did.expect_local(), visibility, field_ev).ty();
1645                }
1646            }
1647            // Subitems of foreign modules have their own publicity.
1648            DefKind::ForeignMod => {}
1649            // An inherent impl is public when its type is public
1650            // Subitems of inherent impls have their own publicity.
1651            // A trait impl is public when both its type and its trait are public
1652            // Subitems of trait impls have inherited publicity.
1653            DefKind::Impl { of_trait } => {
1654                let impl_vis =
1655                    ty::Visibility::of_impl::<false>(def_id, of_trait, tcx, &Default::default());
1656
1657                // We are using the non-shallow version here, unlike when building the
1658                // effective visisibilities table to avoid large number of false positives.
1659                // For example in
1660                //
1661                // impl From<Priv> for Pub {
1662                //     fn from(_: Priv) -> Pub {...}
1663                // }
1664                //
1665                // lints shouldn't be emitted even if `from` effective visibility
1666                // is larger than `Priv` nominal visibility and if `Priv` can leak
1667                // in some scenarios due to type inference.
1668                let impl_ev = EffectiveVisibility::of_impl::<false>(
1669                    def_id,
1670                    of_trait,
1671                    tcx,
1672                    self.effective_visibilities,
1673                );
1674
1675                let mut check = self.check(def_id, impl_vis, Some(impl_ev));
1676
1677                // Generics and clauses of trait impls are intentionally not checked
1678                // for private components (#90586).
1679                if !of_trait {
1680                    check.generics().clauses();
1681                }
1682
1683                // Skip checking private components in associated types, due to lack of full
1684                // normalization they produce very ridiculous false positives.
1685                // FIXME: Remove this when full normalization is implemented.
1686                check.skip_assoc_tys = true;
1687                check.ty();
1688                if of_trait {
1689                    check.trait_ref();
1690                }
1691
1692                for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() {
1693                    let impl_item_vis = if !of_trait {
1694                        min(tcx.local_visibility(assoc_item.def_id.expect_local()), impl_vis, tcx)
1695                    } else {
1696                        impl_vis
1697                    };
1698
1699                    let impl_item_ev = if !of_trait {
1700                        self.get(assoc_item.def_id.expect_local())
1701                            .map(|ev| ev.min(impl_ev, self.tcx))
1702                    } else {
1703                        Some(impl_ev)
1704                    };
1705
1706                    self.check_assoc_item(assoc_item, impl_item_vis, impl_item_ev);
1707                }
1708            }
1709            _ => {}
1710        }
1711    }
1712
1713    fn check_foreign_item(&self, id: ForeignItemId) {
1714        let tcx = self.tcx;
1715        let def_id = id.owner_id.def_id;
1716        let item_visibility = tcx.local_visibility(def_id);
1717        let effective_vis = self.get(def_id);
1718
1719        if let DefKind::ForeignTy = self.tcx.def_kind(def_id) {
1720            self.check_unnameable(def_id, effective_vis);
1721        }
1722
1723        self.check(def_id, item_visibility, effective_vis).generics().clauses().ty();
1724    }
1725}
1726
1727pub fn provide(providers: &mut Providers) {
1728    *providers = Providers {
1729        effective_visibilities,
1730        check_private_in_public,
1731        check_mod_privacy,
1732        ..*providers
1733    };
1734}
1735
1736fn check_mod_privacy(tcx: TyCtxt<'_>, mod_id: LocalModId) {
1737    // Check privacy of names not checked in previous compilation stages.
1738    let mut visitor = NamePrivacyVisitor { tcx, mod_id, maybe_typeck_results: None };
1739    tcx.hir_visit_item_likes_in_module(mod_id, &mut visitor);
1740
1741    // Check privacy of explicitly written types and traits as well as
1742    // inferred types of expressions and patterns.
1743    let span = tcx.def_span(mod_id);
1744    let mut visitor = TypePrivacyVisitor {
1745        tcx,
1746        mod_id,
1747        maybe_typeck_results: None,
1748        span,
1749        accessible_tys: Default::default(),
1750    };
1751
1752    let module = tcx.hir_module_items(mod_id);
1753    for def_id in module.definitions() {
1754        let _ = rustc_ty_walk::walk_types(tcx, def_id, &mut visitor);
1755
1756        if let Some(body_id) = tcx.hir_maybe_body_owned_by(def_id) {
1757            visitor.visit_nested_body(body_id.id());
1758        }
1759
1760        if let DefKind::Impl { of_trait: true } = tcx.def_kind(def_id) {
1761            let trait_ref = tcx.impl_trait_ref(def_id);
1762            let trait_ref = trait_ref.instantiate_identity().skip_norm_wip();
1763            visitor.span =
1764                tcx.hir_expect_item(def_id).expect_impl().of_trait.unwrap().trait_ref.path.span;
1765            let _ =
1766                visitor.visit_def_id(trait_ref.def_id, "trait", &trait_ref.print_only_trait_path());
1767        }
1768    }
1769}
1770
1771fn effective_visibilities(tcx: TyCtxt<'_>, (): ()) -> &EffectiveVisibilities {
1772    let def_ids_to_impls = DefIdsToImplsCollector::collect(tcx);
1773
1774    // Build up a set of all exported items in the AST. This is a set of all
1775    // items which are reachable from external crates based on visibility.
1776    let mut visitor = EmbargoVisitor {
1777        tcx,
1778        effective_visibilities: tcx.resolutions(()).effective_visibilities.clone(),
1779        queue: Default::default(),
1780        def_ids_to_impls,
1781    };
1782
1783    visitor.effective_visibilities.check_invariants(tcx);
1784
1785    // HACK(jynelson): trying to infer the type of `impl Trait` breaks `async-std` (and
1786    // `pub async fn` in general). Since rustdoc never needs to do codegen and doesn't
1787    // care about link-time reachability, keep them unreachable (issue #75100).
1788    let impl_trait_pass = !tcx.sess.opts.actually_rustdoc;
1789    if impl_trait_pass {
1790        // Underlying types of `impl Trait`s are marked as reachable unconditionally,
1791        // so this pass doesn't need to be a part of the fixed point iteration below.
1792        let krate = tcx.hir_crate_items(());
1793        for id in krate.opaques() {
1794            let opaque = tcx.hir_node_by_def_id(id).expect_opaque_ty();
1795            let should_visit = match opaque.origin {
1796                hir::OpaqueTyOrigin::FnReturn {
1797                    parent,
1798                    in_trait_or_impl: Some(hir::RpitContext::Trait),
1799                }
1800                | hir::OpaqueTyOrigin::AsyncFn {
1801                    parent,
1802                    in_trait_or_impl: Some(hir::RpitContext::Trait),
1803                } => match tcx.hir_node_by_def_id(parent).expect_trait_item().expect_fn().1 {
1804                    hir::TraitFn::Required(_) => false,
1805                    hir::TraitFn::Provided(..) => true,
1806                },
1807
1808                // Always visit RPITs in functions that have definitions,
1809                // and all TAITs.
1810                hir::OpaqueTyOrigin::FnReturn {
1811                    in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
1812                    ..
1813                }
1814                | hir::OpaqueTyOrigin::AsyncFn {
1815                    in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
1816                    ..
1817                }
1818                | hir::OpaqueTyOrigin::TyAlias { .. } => true,
1819            };
1820            if should_visit {
1821                // FIXME: This is some serious pessimization intended to workaround deficiencies
1822                // in the reachability pass (`middle/reachable.rs`). Types are marked as link-time
1823                // reachable if they are returned via `impl Trait`, even from private functions.
1824                let pub_ev = EffectiveVisibility::from_vis(ty::Visibility::Public);
1825                visitor.reach_through_impl_trait(opaque.def_id, pub_ev).generics().clauses().ty();
1826            }
1827        }
1828
1829        visitor.queue.clear();
1830    }
1831
1832    // FIXME: remove this once proper support for defs reachability from macros is implemented.
1833    // See `ResolverGlobalCtxt::macro_reachable_adts` comment.
1834    for (&adt_def_id, macro_mods) in &tcx.resolutions(()).macro_reachable_adts {
1835        let struct_def = tcx.adt_def(adt_def_id);
1836        let Some(struct_ev) = visitor.effective_visibilities.effective_vis(adt_def_id).copied()
1837        else {
1838            continue;
1839        };
1840        for field in &struct_def.non_enum_variant().fields {
1841            let def_id = field.did.expect_local();
1842            let field_vis = tcx.local_visibility(def_id);
1843
1844            for &macro_mod in macro_mods {
1845                if field_vis.is_accessible_from(macro_mod, tcx) {
1846                    visitor.reach(def_id, struct_ev).ty();
1847                }
1848            }
1849        }
1850    }
1851
1852    let crate_items = tcx.hir_crate_items(());
1853    for id in crate_items.free_items() {
1854        visitor.check_def_id(id.owner_id.def_id);
1855    }
1856    for id in crate_items.foreign_items() {
1857        visitor.check_def_id(id.owner_id.def_id);
1858    }
1859    while let Some(def_id) = visitor.queue.pop() {
1860        visitor.check_def_id(def_id);
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<'_>, mod_id: LocalModId) {
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(mod_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}