Skip to main content

rustc_privacy/
lib.rs

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