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, kw, 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::unreachable_default_msg(),
            }, &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 = ty::Visibility::Restricted(self.tcx.parent_module_from_def_id(def_id));
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::Tool(..) |
                            ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                            {}
                            #[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                            // kw::Underscore is a `Self` mapping delegation field which is
1081                            // generated by compiler, see delegation AST -> HIR lowering code
1082                            // and `check_expr_struct_fields` for details.
1083                            let name = match field.ident.name {
1084                                kw::Underscore => variant.fields[index].name,
1085                                name => name,
1086                            };
1087                            failed_fields.push((name, field.ident.span, true));
1088                        }
1089                    }
1090                    self.emit_unreachable_field_error(failed_fields, adt, None, qpath.span());
1091                }
1092            }
1093        }
1094
1095        intravisit::walk_expr(self, expr);
1096    }
1097
1098    fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
1099        if let PatKind::Struct(ref qpath, fields, _) = pat.kind {
1100            let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
1101            let adt = self.typeck_results().pat_ty(pat).ty_adt_def().unwrap();
1102            let variant = adt.variant_of_res(res);
1103            let mut failed_fields = ::alloc::vec::Vec::new()vec![];
1104            for field in fields {
1105                let index = self.typeck_results().field_index(field.hir_id);
1106                if self.check_field(field.ident.span, adt, &variant.fields[index]) {
1107                    failed_fields.push((field.ident.name, field.ident.span, true));
1108                }
1109            }
1110            self.emit_unreachable_field_error(failed_fields, adt, None, qpath.span());
1111        }
1112
1113        intravisit::walk_pat(self, pat);
1114    }
1115}
1116
1117/// Type privacy visitor, checks types for privacy and reports violations.
1118///
1119/// Both explicitly written types and inferred types of expressions and patterns are checked.
1120/// Checks are performed on "semantic" types regardless of names and their hygiene.
1121struct TypePrivacyVisitor<'tcx> {
1122    tcx: TyCtxt<'tcx>,
1123    mod_id: LocalModId,
1124    maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
1125    span: Span,
1126    /// Types already walked clean (no privacy error). A walk's result depends only on the
1127    /// interned type and `mod_id`, which is fixed for the whole visit, so a type that walks
1128    /// clean once walks clean everywhere and we can skip it. Errored walks are never cached,
1129    /// so their error still fires at every span.
1130    accessible_tys: FxHashSet<Ty<'tcx>>,
1131}
1132
1133impl<'tcx> TypePrivacyVisitor<'tcx> {
1134    fn item_is_accessible(&self, did: DefId) -> bool {
1135        self.tcx.visibility(did).is_accessible_from(self.mod_id, self.tcx)
1136    }
1137
1138    fn check_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<()> {
1139        if self.accessible_tys.contains(&ty) {
1140            return ControlFlow::Continue(());
1141        }
1142        self.visit(ty)?;
1143        self.accessible_tys.insert(ty);
1144        ControlFlow::Continue(())
1145    }
1146
1147    // Take node-id of an expression or pattern and check its type for privacy.
1148    fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
1149        self.span = span;
1150        let typeck_results = self
1151            .maybe_typeck_results
1152            .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"));
1153        try {
1154            self.check_ty(typeck_results.node_type(id))?;
1155            self.visit(typeck_results.node_args(id))?;
1156            if let Some(adjustments) = typeck_results.adjustments().get(id) {
1157                adjustments.iter().try_for_each(|adjustment| self.check_ty(adjustment.target))?;
1158            }
1159        }
1160        .is_break()
1161    }
1162
1163    fn check_def_id(&self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1164        let is_error = !self.item_is_accessible(def_id);
1165        if is_error {
1166            self.tcx.dcx().emit_err(ItemIsPrivate { span: self.span, kind, descr: descr.into() });
1167        }
1168        is_error
1169    }
1170}
1171
1172impl<'tcx> rustc_ty_walk::SpannedTypeVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1173    type Result = ControlFlow<()>;
1174    fn visit(&mut self, span: Span, value: impl TypeVisitable<TyCtxt<'tcx>>) -> Self::Result {
1175        self.span = span;
1176        value.visit_with(&mut self.skeleton())
1177    }
1178}
1179
1180impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> {
1181    fn visit_nested_body(&mut self, body_id: hir::BodyId) {
1182        let old_maybe_typeck_results =
1183            self.maybe_typeck_results.replace(self.tcx.typeck_body(body_id));
1184        self.visit_body(self.tcx.hir_body(body_id));
1185        self.maybe_typeck_results = old_maybe_typeck_results;
1186    }
1187
1188    fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx, AmbigArg>) {
1189        self.span = hir_ty.span;
1190        let ty = self
1191            .maybe_typeck_results
1192            .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"))
1193            .node_type(hir_ty.hir_id);
1194        if self.check_ty(ty).is_break() {
1195            return;
1196        }
1197
1198        intravisit::walk_ty(self, hir_ty);
1199    }
1200
1201    fn visit_infer(
1202        &mut self,
1203        inf_id: rustc_hir::HirId,
1204        inf_span: Span,
1205        _kind: InferKind<'tcx>,
1206    ) -> Self::Result {
1207        self.span = inf_span;
1208        if let Some(ty) = self
1209            .maybe_typeck_results
1210            .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"))
1211            .node_type_opt(inf_id)
1212        {
1213            if self.check_ty(ty).is_break() {
1214                return;
1215            }
1216        } else {
1217            // FIXME: check types of const infers here.
1218        }
1219
1220        self.visit_id(inf_id)
1221    }
1222
1223    // Check types of expressions
1224    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1225        if self.check_expr_pat_type(expr.hir_id, expr.span) {
1226            // Do not check nested expressions if the error already happened.
1227            return;
1228        }
1229        match expr.kind {
1230            hir::ExprKind::Assign(_, rhs, _) | hir::ExprKind::Match(rhs, ..) => {
1231                // Do not report duplicate errors for `x = y` and `match x { ... }`.
1232                if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
1233                    return;
1234                }
1235            }
1236            hir::ExprKind::MethodCall(segment, ..) => {
1237                // Method calls have to be checked specially.
1238                self.span = segment.ident.span;
1239                let typeck_results = self
1240                    .maybe_typeck_results
1241                    .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"));
1242                if let Some(def_id) = typeck_results.type_dependent_def_id(expr.hir_id) {
1243                    if self
1244                        .check_ty(self.tcx.type_of(def_id).instantiate_identity().skip_norm_wip())
1245                        .is_break()
1246                    {
1247                        return;
1248                    }
1249                } else {
1250                    self.tcx
1251                        .dcx()
1252                        .span_delayed_bug(expr.span, "no type-dependent def for method call");
1253                }
1254            }
1255            _ => {}
1256        }
1257
1258        intravisit::walk_expr(self, expr);
1259    }
1260
1261    // Prohibit access to associated items with insufficient nominal visibility.
1262    //
1263    // Additionally, until better reachability analysis for macros 2.0 is available,
1264    // we prohibit access to private statics from other crates, this allows to give
1265    // more code internal visibility at link time. (Access to private functions
1266    // is already prohibited by type privacy for function types.)
1267    fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) {
1268        let def = match qpath {
1269            hir::QPath::Resolved(_, path) => match path.res {
1270                Res::Def(kind, def_id) => Some((kind, def_id)),
1271                _ => None,
1272            },
1273            hir::QPath::TypeRelative(..) => {
1274                match self.maybe_typeck_results {
1275                    Some(typeck_results) => typeck_results.type_dependent_def(id),
1276                    // FIXME: Check type-relative associated types in signatures.
1277                    None => None,
1278                }
1279            }
1280        };
1281        let def = def.filter(|(kind, _)| {
1282            #[allow(non_exhaustive_omitted_patterns)] match kind {
    DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy |
        DefKind::Static { .. } => true,
    _ => false,
}matches!(
1283                kind,
1284                DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static { .. }
1285            )
1286        });
1287        if let Some((kind, def_id)) = def {
1288            let is_local_static =
1289                if let DefKind::Static { .. } = kind { def_id.is_local() } else { false };
1290            if !self.item_is_accessible(def_id) && !is_local_static {
1291                let name = match *qpath {
1292                    hir::QPath::Resolved(_, path) => Some(self.tcx.def_path_str(path.res.def_id())),
1293                    hir::QPath::TypeRelative(_, segment) => Some(segment.ident.to_string()),
1294                };
1295                let kind = self.tcx.def_descr(def_id);
1296                let sess = self.tcx.sess;
1297                let _ = match name {
1298                    Some(name) => {
1299                        sess.dcx().emit_err(ItemIsPrivate { span, kind, descr: (&name).into() })
1300                    }
1301                    None => sess.dcx().emit_err(UnnamedItemIsPrivate { span, kind }),
1302                };
1303                return;
1304            }
1305        }
1306
1307        intravisit::walk_qpath(self, qpath, id);
1308    }
1309
1310    // Check types of patterns.
1311    fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) {
1312        if self.check_expr_pat_type(pattern.hir_id, pattern.span) {
1313            // Do not check nested patterns if the error already happened.
1314            return;
1315        }
1316
1317        intravisit::walk_pat(self, pattern);
1318    }
1319
1320    fn visit_local(&mut self, local: &'tcx hir::LetStmt<'tcx>) {
1321        if let Some(init) = local.init {
1322            if self.check_expr_pat_type(init.hir_id, init.span) {
1323                // Do not report duplicate errors for `let x = y`.
1324                return;
1325            }
1326        }
1327
1328        intravisit::walk_local(self, local);
1329    }
1330}
1331
1332impl<'tcx> DefIdVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1333    type Result = ControlFlow<()>;
1334    fn tcx(&self) -> TyCtxt<'tcx> {
1335        self.tcx
1336    }
1337    fn visit_def_id(
1338        &mut self,
1339        def_id: DefId,
1340        kind: &str,
1341        descr: &dyn fmt::Display,
1342    ) -> Self::Result {
1343        if self.check_def_id(def_id, kind, descr) {
1344            ControlFlow::Break(())
1345        } else {
1346            ControlFlow::Continue(())
1347        }
1348    }
1349}
1350
1351/// SearchInterfaceForPrivateItemsVisitor traverses an item's interface and
1352/// finds any private components in it.
1353///
1354/// PrivateItemsInPublicInterfacesVisitor ensures there are no private types
1355/// and traits in public interfaces.
1356struct SearchInterfaceForPrivateItemsVisitor<'tcx> {
1357    tcx: TyCtxt<'tcx>,
1358    item_def_id: LocalDefId,
1359    /// The visitor checks that each component type is at least this visible.
1360    required_visibility: ty::Visibility,
1361    required_effective_vis: Option<EffectiveVisibility>,
1362    hard_error: bool = false,
1363    in_primary_interface: bool = true,
1364    skip_assoc_tys: bool = false,
1365}
1366
1367impl SearchInterfaceForPrivateItemsVisitor<'_> {
1368    fn generics(&mut self) -> &mut Self {
1369        self.in_primary_interface = true;
1370        for param in &self.tcx.generics_of(self.item_def_id).own_params {
1371            if let GenericParamDefKind::Const { .. } = param.kind {
1372                let _ = self
1373                    .visit(self.tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip());
1374            }
1375            if let Some(default) = param.default_value(self.tcx) {
1376                let _ = self.visit(default.instantiate_identity().skip_norm_wip());
1377            }
1378        }
1379        self
1380    }
1381
1382    fn clauses(&mut self) -> &mut Self {
1383        self.in_primary_interface = false;
1384        // N.B., we use `explicit_clauses_of` and not `clauses_of`
1385        // because we don't want to report privacy errors due to where
1386        // clauses that the compiler inferred. We only want to
1387        // consider the ones that the user wrote. This is important
1388        // for the inferred outlives rules; see
1389        // `tests/ui/rfc-2093-infer-outlives/privacy.rs`.
1390        let _ = self.visit_gen_clauses(self.tcx.explicit_clauses_of(self.item_def_id));
1391        self
1392    }
1393
1394    fn bounds(&mut self) -> &mut Self {
1395        self.in_primary_interface = false;
1396        let _ = self.visit_clauses(self.tcx.explicit_item_bounds(self.item_def_id).skip_binder());
1397        self
1398    }
1399
1400    fn ty(&mut self) -> &mut Self {
1401        self.in_primary_interface = true;
1402        let _ =
1403            self.visit(self.tcx.type_of(self.item_def_id).instantiate_identity().skip_norm_wip());
1404        self
1405    }
1406
1407    fn trait_ref(&mut self) -> &mut Self {
1408        self.in_primary_interface = true;
1409        let _ = self.visit_trait(
1410            self.tcx.impl_trait_ref(self.item_def_id).instantiate_identity().skip_norm_wip(),
1411        );
1412        self
1413    }
1414
1415    fn check_def_id(&self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1416        if self.leaks_private_dep(def_id) {
1417            self.tcx.emit_node_span_lint(
1418                EXPORTED_PRIVATE_DEPENDENCIES,
1419                self.tcx.local_def_id_to_hir_id(self.item_def_id),
1420                self.tcx.def_span(self.item_def_id.to_def_id()),
1421                FromPrivateDependencyInPublicInterface {
1422                    kind,
1423                    descr: descr.into(),
1424                    krate: self.tcx.crate_name(def_id.krate),
1425                },
1426            );
1427        }
1428
1429        let Some(local_def_id) = def_id.as_local() else {
1430            return false;
1431        };
1432
1433        let vis = self.tcx.local_visibility(local_def_id);
1434        if self.hard_error && self.required_visibility.greater_than(vis, self.tcx) {
1435            let vis_descr = match vis {
1436                ty::Visibility::Public => "public",
1437                ty::Visibility::Restricted(vis_mod_id) => {
1438                    if vis_mod_id == self.tcx.parent_module_from_def_id(local_def_id) {
1439                        "private"
1440                    } else if vis_mod_id.is_top_level_module() {
1441                        "crate-private"
1442                    } else {
1443                        "restricted"
1444                    }
1445                }
1446            };
1447
1448            let span = self.tcx.def_span(self.item_def_id.to_def_id());
1449            let vis_span = self.tcx.def_span(def_id);
1450            self.tcx.dcx().emit_err(InPublicInterface {
1451                span,
1452                vis_descr,
1453                kind,
1454                descr: descr.into(),
1455                vis_span,
1456            });
1457            return false;
1458        }
1459
1460        let Some(effective_vis) = self.required_effective_vis else {
1461            return false;
1462        };
1463
1464        let reachable_at_vis = *effective_vis.at_level(Level::Reachable);
1465
1466        if reachable_at_vis.greater_than(vis, self.tcx) {
1467            let lint = if self.in_primary_interface { PRIVATE_INTERFACES } else { PRIVATE_BOUNDS };
1468            let span = self.tcx.def_span(self.item_def_id.to_def_id());
1469            let vis_span = self.tcx.def_span(def_id);
1470            self.tcx.emit_node_span_lint(
1471                lint,
1472                self.tcx.local_def_id_to_hir_id(self.item_def_id),
1473                span,
1474                PrivateInterfacesOrBoundsLint {
1475                    item_span: span,
1476                    item_kind: self.tcx.def_descr(self.item_def_id.to_def_id()),
1477                    item_descr: (&LazyDefPathStr {
1478                        def_id: self.item_def_id.to_def_id(),
1479                        tcx: self.tcx,
1480                    })
1481                        .into(),
1482                    item_vis_descr: &reachable_at_vis.to_string(self.item_def_id, self.tcx),
1483                    ty_span: vis_span,
1484                    ty_kind: kind,
1485                    ty_descr: descr.into(),
1486                    ty_vis_descr: &vis.to_string(local_def_id, self.tcx),
1487                },
1488            );
1489        }
1490
1491        false
1492    }
1493
1494    /// An item is 'leaked' from a private dependency if all
1495    /// of the following are true:
1496    /// 1. It's contained within a public type
1497    /// 2. It comes from a private crate
1498    fn leaks_private_dep(&self, item_id: DefId) -> bool {
1499        let ret = self.required_visibility.is_public() && self.tcx.is_private_dep(item_id.krate);
1500
1501        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/1c3a6506966e21845b31de0b075d2527660db132/compiler/rustc_privacy/src/lib.rs:1501",
                        "rustc_privacy", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/1c3a6506966e21845b31de0b075d2527660db132/compiler/rustc_privacy/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1501u32),
                        ::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);
1502        ret
1503    }
1504}
1505
1506impl<'tcx> DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> {
1507    type Result = ControlFlow<()>;
1508    fn skip_assoc_tys(&self) -> bool {
1509        self.skip_assoc_tys
1510    }
1511    fn tcx(&self) -> TyCtxt<'tcx> {
1512        self.tcx
1513    }
1514    fn visit_def_id(
1515        &mut self,
1516        def_id: DefId,
1517        kind: &str,
1518        descr: &dyn fmt::Display,
1519    ) -> Self::Result {
1520        if self.check_def_id(def_id, kind, descr) {
1521            ControlFlow::Break(())
1522        } else {
1523            ControlFlow::Continue(())
1524        }
1525    }
1526}
1527
1528struct PrivateItemsInPublicInterfacesChecker<'a, 'tcx> {
1529    tcx: TyCtxt<'tcx>,
1530    effective_visibilities: &'a EffectiveVisibilities,
1531}
1532
1533impl<'tcx> PrivateItemsInPublicInterfacesChecker<'_, 'tcx> {
1534    fn check(
1535        &self,
1536        def_id: LocalDefId,
1537        required_visibility: ty::Visibility,
1538        required_effective_vis: Option<EffectiveVisibility>,
1539    ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> {
1540        SearchInterfaceForPrivateItemsVisitor {
1541            tcx: self.tcx,
1542            item_def_id: def_id,
1543            required_visibility,
1544            required_effective_vis,
1545            ..
1546        }
1547    }
1548
1549    fn check_unnameable(&self, def_id: LocalDefId, effective_vis: Option<EffectiveVisibility>) {
1550        let Some(effective_vis) = effective_vis else {
1551            return;
1552        };
1553
1554        let reexported_at_vis = effective_vis.at_level(Level::Reexported);
1555        let reachable_at_vis = effective_vis.at_level(Level::Reachable);
1556
1557        if reachable_at_vis.is_public() && reexported_at_vis != reachable_at_vis {
1558            let hir_id = self.tcx.local_def_id_to_hir_id(def_id);
1559            let span = self.tcx.def_span(def_id.to_def_id());
1560            self.tcx.emit_node_span_lint(
1561                UNNAMEABLE_TYPES,
1562                hir_id,
1563                span,
1564                UnnameableTypesLint {
1565                    span,
1566                    kind: self.tcx.def_descr(def_id.to_def_id()),
1567                    descr: (&LazyDefPathStr { def_id: def_id.to_def_id(), tcx: self.tcx }).into(),
1568                    reachable_vis: &reachable_at_vis.to_string(def_id, self.tcx),
1569                    reexported_vis: &reexported_at_vis.to_string(def_id, self.tcx),
1570                },
1571            );
1572        }
1573    }
1574
1575    fn check_assoc_item(
1576        &self,
1577        item: &ty::AssocItem,
1578        vis: ty::Visibility,
1579        effective_vis: Option<EffectiveVisibility>,
1580    ) {
1581        let mut check = self.check(item.def_id.expect_local(), vis, effective_vis);
1582
1583        let is_assoc_ty = item.is_type();
1584        check.hard_error = is_assoc_ty;
1585        check.generics().clauses();
1586        if assoc_has_type_of(self.tcx, item) {
1587            check.ty();
1588        }
1589        if is_assoc_ty && item.container == AssocContainer::Trait {
1590            // FIXME: too much breakage from reporting hard errors here, better wait for a fix
1591            // from proper associated type normalization.
1592            check.hard_error = false;
1593            check.bounds();
1594        }
1595    }
1596
1597    fn get(&self, def_id: LocalDefId) -> Option<EffectiveVisibility> {
1598        self.effective_visibilities.effective_vis(def_id).copied()
1599    }
1600
1601    fn check_item(&self, id: ItemId) {
1602        let tcx = self.tcx;
1603        let def_id = id.owner_id.def_id;
1604        let item_visibility = tcx.local_visibility(def_id);
1605        let effective_vis = self.get(def_id);
1606        let def_kind = tcx.def_kind(def_id);
1607
1608        match def_kind {
1609            DefKind::Const | DefKind::Static { .. } | DefKind::Fn | DefKind::TyAlias => {
1610                if let DefKind::TyAlias = def_kind {
1611                    self.check_unnameable(def_id, effective_vis);
1612                }
1613                self.check(def_id, item_visibility, effective_vis).generics().clauses().ty();
1614            }
1615            DefKind::OpaqueTy => {
1616                // `ty()` for opaque types is the underlying type,
1617                // it's not a part of interface, so we skip it.
1618                self.check(def_id, item_visibility, effective_vis).generics().bounds();
1619            }
1620            DefKind::Trait => {
1621                self.check_unnameable(def_id, effective_vis);
1622
1623                self.check(def_id, item_visibility, effective_vis).generics().clauses();
1624
1625                for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() {
1626                    self.check_assoc_item(assoc_item, item_visibility, effective_vis);
1627                }
1628            }
1629            DefKind::TraitAlias => {
1630                self.check(def_id, item_visibility, effective_vis).generics().clauses();
1631            }
1632            DefKind::Enum => {
1633                self.check_unnameable(def_id, effective_vis);
1634                self.check(def_id, item_visibility, effective_vis).generics().clauses();
1635
1636                let adt = tcx.adt_def(id.owner_id);
1637                for field in adt.all_fields() {
1638                    self.check(field.did.expect_local(), item_visibility, effective_vis).ty();
1639                }
1640            }
1641            // Subitems of structs and unions have their own publicity.
1642            DefKind::Struct | DefKind::Union => {
1643                self.check_unnameable(def_id, effective_vis);
1644                self.check(def_id, item_visibility, effective_vis).generics().clauses();
1645
1646                let adt = tcx.adt_def(id.owner_id);
1647                for field in adt.all_fields() {
1648                    let visibility = min(item_visibility, field.vis.expect_local(), tcx);
1649                    let field_ev = self.get(field.did.expect_local());
1650
1651                    self.check(field.did.expect_local(), visibility, field_ev).ty();
1652                }
1653            }
1654            // Subitems of foreign modules have their own publicity.
1655            DefKind::ForeignMod => {}
1656            // An inherent impl is public when its type is public
1657            // Subitems of inherent impls have their own publicity.
1658            // A trait impl is public when both its type and its trait are public
1659            // Subitems of trait impls have inherited publicity.
1660            DefKind::Impl { of_trait } => {
1661                let impl_vis =
1662                    ty::Visibility::of_impl::<false>(def_id, of_trait, tcx, &Default::default());
1663
1664                // We are using the non-shallow version here, unlike when building the
1665                // effective visisibilities table to avoid large number of false positives.
1666                // For example in
1667                //
1668                // impl From<Priv> for Pub {
1669                //     fn from(_: Priv) -> Pub {...}
1670                // }
1671                //
1672                // lints shouldn't be emitted even if `from` effective visibility
1673                // is larger than `Priv` nominal visibility and if `Priv` can leak
1674                // in some scenarios due to type inference.
1675                let impl_ev = EffectiveVisibility::of_impl::<false>(
1676                    def_id,
1677                    of_trait,
1678                    tcx,
1679                    self.effective_visibilities,
1680                );
1681
1682                let mut check = self.check(def_id, impl_vis, Some(impl_ev));
1683
1684                // Generics and clauses of trait impls are intentionally not checked
1685                // for private components (#90586).
1686                if !of_trait {
1687                    check.generics().clauses();
1688                }
1689
1690                // Skip checking private components in associated types, due to lack of full
1691                // normalization they produce very ridiculous false positives.
1692                // FIXME: Remove this when full normalization is implemented.
1693                check.skip_assoc_tys = true;
1694                check.ty();
1695                if of_trait {
1696                    check.trait_ref();
1697                }
1698
1699                for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() {
1700                    let impl_item_vis = if !of_trait {
1701                        min(tcx.local_visibility(assoc_item.def_id.expect_local()), impl_vis, tcx)
1702                    } else {
1703                        impl_vis
1704                    };
1705
1706                    let impl_item_ev = if !of_trait {
1707                        self.get(assoc_item.def_id.expect_local())
1708                            .map(|ev| ev.min(impl_ev, self.tcx))
1709                    } else {
1710                        Some(impl_ev)
1711                    };
1712
1713                    self.check_assoc_item(assoc_item, impl_item_vis, impl_item_ev);
1714                }
1715            }
1716            _ => {}
1717        }
1718    }
1719
1720    fn check_foreign_item(&self, id: ForeignItemId) {
1721        let tcx = self.tcx;
1722        let def_id = id.owner_id.def_id;
1723        let item_visibility = tcx.local_visibility(def_id);
1724        let effective_vis = self.get(def_id);
1725
1726        if let DefKind::ForeignTy = self.tcx.def_kind(def_id) {
1727            self.check_unnameable(def_id, effective_vis);
1728        }
1729
1730        self.check(def_id, item_visibility, effective_vis).generics().clauses().ty();
1731    }
1732}
1733
1734pub fn provide(providers: &mut Providers) {
1735    *providers = Providers {
1736        effective_visibilities,
1737        check_private_in_public,
1738        check_mod_privacy,
1739        ..*providers
1740    };
1741}
1742
1743fn check_mod_privacy(tcx: TyCtxt<'_>, mod_id: LocalModId) {
1744    // Check privacy of names not checked in previous compilation stages.
1745    let mut visitor = NamePrivacyVisitor { tcx, mod_id, maybe_typeck_results: None };
1746    tcx.hir_visit_item_likes_in_module(mod_id, &mut visitor);
1747
1748    // Check privacy of explicitly written types and traits as well as
1749    // inferred types of expressions and patterns.
1750    let span = tcx.def_span(mod_id);
1751    let mut visitor = TypePrivacyVisitor {
1752        tcx,
1753        mod_id,
1754        maybe_typeck_results: None,
1755        span,
1756        accessible_tys: Default::default(),
1757    };
1758
1759    let module = tcx.hir_module_items(mod_id);
1760    for def_id in module.definitions() {
1761        let _ = rustc_ty_walk::walk_types(tcx, def_id, &mut visitor);
1762
1763        if let Some(body_id) = tcx.hir_maybe_body_owned_by(def_id) {
1764            visitor.visit_nested_body(body_id.id());
1765        }
1766
1767        if let DefKind::Impl { of_trait: true } = tcx.def_kind(def_id) {
1768            let trait_ref = tcx.impl_trait_ref(def_id);
1769            let trait_ref = trait_ref.instantiate_identity().skip_norm_wip();
1770            visitor.span =
1771                tcx.hir_expect_item(def_id).expect_impl().of_trait.unwrap().trait_ref.path.span;
1772            let _ =
1773                visitor.visit_def_id(trait_ref.def_id, "trait", &trait_ref.print_only_trait_path());
1774        }
1775    }
1776}
1777
1778fn effective_visibilities(tcx: TyCtxt<'_>, (): ()) -> &EffectiveVisibilities {
1779    let def_ids_to_impls = DefIdsToImplsCollector::collect(tcx);
1780
1781    // Build up a set of all exported items in the AST. This is a set of all
1782    // items which are reachable from external crates based on visibility.
1783    let mut visitor = EmbargoVisitor {
1784        tcx,
1785        effective_visibilities: tcx.resolutions(()).effective_visibilities.clone(),
1786        queue: Default::default(),
1787        def_ids_to_impls,
1788    };
1789
1790    visitor.effective_visibilities.check_invariants(tcx);
1791
1792    // HACK(jynelson): trying to infer the type of `impl Trait` breaks `async-std` (and
1793    // `pub async fn` in general). Since rustdoc never needs to do codegen and doesn't
1794    // care about link-time reachability, keep them unreachable (issue #75100).
1795    let impl_trait_pass = !tcx.sess.opts.actually_rustdoc;
1796    if impl_trait_pass {
1797        // Underlying types of `impl Trait`s are marked as reachable unconditionally,
1798        // so this pass doesn't need to be a part of the fixed point iteration below.
1799        let krate = tcx.hir_crate_items(());
1800        for id in krate.opaques() {
1801            let opaque = tcx.hir_node_by_def_id(id).expect_opaque_ty();
1802            let should_visit = match opaque.origin {
1803                hir::OpaqueTyOrigin::FnReturn {
1804                    parent,
1805                    in_trait_or_impl: Some(hir::RpitContext::Trait),
1806                }
1807                | hir::OpaqueTyOrigin::AsyncFn {
1808                    parent,
1809                    in_trait_or_impl: Some(hir::RpitContext::Trait),
1810                } => match tcx.hir_node_by_def_id(parent).expect_trait_item().expect_fn().1 {
1811                    hir::TraitFn::Required(_) => false,
1812                    hir::TraitFn::Provided(..) => true,
1813                },
1814
1815                // Always visit RPITs in functions that have definitions,
1816                // and all TAITs.
1817                hir::OpaqueTyOrigin::FnReturn {
1818                    in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
1819                    ..
1820                }
1821                | hir::OpaqueTyOrigin::AsyncFn {
1822                    in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
1823                    ..
1824                }
1825                | hir::OpaqueTyOrigin::TyAlias { .. } => true,
1826            };
1827            if should_visit {
1828                // FIXME: This is some serious pessimization intended to workaround deficiencies
1829                // in the reachability pass (`middle/reachable.rs`). Types are marked as link-time
1830                // reachable if they are returned via `impl Trait`, even from private functions.
1831                let pub_ev = EffectiveVisibility::from_vis(ty::Visibility::Public);
1832                visitor.reach_through_impl_trait(opaque.def_id, pub_ev).generics().clauses().ty();
1833            }
1834        }
1835
1836        visitor.queue.clear();
1837    }
1838
1839    // FIXME: remove this once proper support for defs reachability from macros is implemented.
1840    // See `ResolverGlobalCtxt::macro_reachable_adts` comment.
1841    for (&adt_def_id, macro_mods) in &tcx.resolutions(()).macro_reachable_adts {
1842        let struct_def = tcx.adt_def(adt_def_id);
1843        let Some(struct_ev) = visitor.effective_visibilities.effective_vis(adt_def_id).copied()
1844        else {
1845            continue;
1846        };
1847        for field in &struct_def.non_enum_variant().fields {
1848            let def_id = field.did.expect_local();
1849            let field_vis = tcx.local_visibility(def_id);
1850
1851            for &macro_mod in macro_mods {
1852                if field_vis.is_accessible_from(macro_mod, tcx) {
1853                    visitor.reach(def_id, struct_ev).ty();
1854                }
1855            }
1856        }
1857    }
1858
1859    let crate_items = tcx.hir_crate_items(());
1860    for id in crate_items.free_items() {
1861        visitor.check_def_id(id.owner_id.def_id);
1862    }
1863    for id in crate_items.foreign_items() {
1864        visitor.check_def_id(id.owner_id.def_id);
1865    }
1866    while let Some(def_id) = visitor.queue.pop() {
1867        visitor.check_def_id(def_id);
1868    }
1869    visitor.effective_visibilities.check_invariants(tcx);
1870
1871    let check_visitor =
1872        TestReachabilityVisitor { tcx, effective_visibilities: &visitor.effective_visibilities };
1873    for id in crate_items.owners() {
1874        check_visitor.check_def_id(id);
1875    }
1876
1877    tcx.arena.alloc(visitor.effective_visibilities)
1878}
1879
1880fn check_private_in_public(tcx: TyCtxt<'_>, mod_id: LocalModId) {
1881    let effective_visibilities = tcx.effective_visibilities(());
1882    // Check for private types in public interfaces.
1883    let checker = PrivateItemsInPublicInterfacesChecker { tcx, effective_visibilities };
1884
1885    let crate_items = tcx.hir_module_items(mod_id);
1886    let _ = crate_items.par_items(|id| Ok(checker.check_item(id)));
1887    let _ = crate_items.par_foreign_items(|id| Ok(checker.check_foreign_item(id)));
1888}