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