Skip to main content

rustc_privacy/
lib.rs

1// tidy-alphabetical-start
2#![feature(associated_type_defaults)]
3#![feature(default_field_values)]
4#![feature(try_blocks)]
5// tidy-alphabetical-end
6
7mod errors;
8
9use std::marker::PhantomData;
10use std::ops::ControlFlow;
11use std::{debug_assert_matches, fmt};
12
13use errors::{
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, LocalModDefId};
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_predicates(&mut self, predicates: ty::GenericPredicates<'tcx>) -> Self::Result {
91        self.skeleton().visit_clauses(predicates.predicates)
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(pred) => {
137                match ::rustc_ast_ir::visit::VisitorResult::branch(self.visit_trait(pred.trait_ref))
    {
    core::ops::ControlFlow::Continue(()) =>
        (),
        #[allow(unreachable_code)]
        core::ops::ControlFlow::Break(r) => {
        return ::rustc_ast_ir::visit::VisitorResult::from_residual(r);
    }
};try_visit!(self.visit_trait(pred.trait_ref));
138                pred.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::OutlivesPredicate(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                data @ ty::AliasTy {
219                    kind:
220                        kind @ (ty::Inherent { def_id }
221                        | ty::Free { def_id }
222                        | ty::Projection { def_id }),
223                    ..
224                },
225            ) => {
226                if self.def_id_visitor.skip_assoc_tys() {
227                    // Visitors searching for minimal visibility/reachability want to
228                    // conservatively approximate associated types like `Type::Alias`
229                    // as visible/reachable even if `Type` is private.
230                    // Ideally, associated types should be instantiated in the same way as
231                    // free type aliases, but this isn't done yet.
232                    return V::Result::output();
233                }
234                if !self.visited_tys.insert(ty) {
235                    // Avoid repeatedly visiting alias types (including projections).
236                    // This helps with special cases like #145741, but doesn't introduce
237                    // too much overhead in general case, unlike caching for other types.
238                    return V::Result::output();
239                }
240
241                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(
242                    def_id,
243                    match kind {
244                        ty::Inherent { .. } | ty::Projection { .. } => "associated type",
245                        ty::Free { .. } => "type alias",
246                        ty::Opaque { .. } => unreachable!(),
247                    },
248                    &LazyDefPathStr { def_id, tcx },
249                ));
250
251                // This will also visit args if necessary, so we don't need to recurse.
252                return if V::SHALLOW {
253                    V::Result::output()
254                } else if #[allow(non_exhaustive_omitted_patterns)] match kind {
    ty::Projection { .. } => true,
    _ => false,
}matches!(kind, ty::Projection { .. }) {
255                    self.visit_projection_term(data.into())
256                } else {
257                    V::Result::from_branch(
258                        data.args.iter().try_for_each(|arg| arg.visit_with(self).branch()),
259                    )
260                };
261            }
262            ty::Dynamic(predicates, ..) => {
263                // All traits in the list are considered the "primary" part of the type
264                // and are visited by shallow visitors.
265                for predicate in predicates {
266                    let trait_ref = match predicate.skip_binder() {
267                        ty::ExistentialPredicate::Trait(trait_ref) => trait_ref,
268                        ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx),
269                        ty::ExistentialPredicate::AutoTrait(def_id) => {
270                            ty::ExistentialTraitRef::new(tcx, def_id, ty::GenericArgs::empty())
271                        }
272                    };
273                    let ty::ExistentialTraitRef { def_id, .. } = trait_ref;
274                    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));
275                }
276            }
277            ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id }, .. }) => {
278                // Skip repeated `Opaque`s to avoid infinite recursion.
279                if self.visited_tys.insert(ty) {
280                    // The intent is to treat `impl Trait1 + Trait2` identically to
281                    // `dyn Trait1 + Trait2`. Therefore we ignore def-id of the opaque type itself
282                    // (it either has no visibility, or its visibility is insignificant, like
283                    // visibilities of type aliases) and recurse into bounds instead to go
284                    // through the trait list (default type visitor doesn't visit those traits).
285                    // All traits in the list are considered the "primary" part of the type
286                    // and are visited by shallow visitors.
287                    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()));
288                }
289            }
290            // These types don't have their own def-ids (but may have subcomponents
291            // with def-ids that should be visited recursively).
292            ty::Bool
293            | ty::Char
294            | ty::Int(..)
295            | ty::Uint(..)
296            | ty::Float(..)
297            | ty::Str
298            | ty::Never
299            | ty::Array(..)
300            | ty::Slice(..)
301            | ty::Tuple(..)
302            | ty::RawPtr(..)
303            | ty::Ref(..)
304            | ty::Pat(..)
305            | ty::FnPtr(..)
306            | ty::UnsafeBinder(_)
307            | ty::Param(..)
308            | ty::Bound(..)
309            | ty::Error(_)
310            | ty::CoroutineWitness(..) => {}
311            ty::Placeholder(..) | ty::Infer(..) => {
312                ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected type: {0:?}", ty))bug!("unexpected type: {:?}", ty)
313            }
314        }
315
316        if V::SHALLOW { V::Result::output() } else { ty.super_visit_with(self) }
317    }
318
319    fn visit_const(&mut self, c: Const<'tcx>) -> Self::Result {
320        let tcx = self.def_id_visitor.tcx();
321        tcx.expand_abstract_consts(c).super_visit_with(self)
322    }
323}
324
325fn assoc_has_type_of(tcx: TyCtxt<'_>, item: &ty::AssocItem) -> bool {
326    if let ty::AssocKind::Type { data: ty::AssocTypeData::Normal(..) } = item.kind
327        && let hir::Node::TraitItem(item) =
328            tcx.hir_node(tcx.local_def_id_to_hir_id(item.def_id.expect_local()))
329        && let hir::TraitItemKind::Type(_, None) = item.kind
330    {
331        false
332    } else {
333        true
334    }
335}
336
337fn min(vis1: ty::Visibility, vis2: ty::Visibility, tcx: TyCtxt<'_>) -> ty::Visibility {
338    if vis1.greater_than(vis2, tcx) { vis2 } else { vis1 }
339}
340
341/// Visitor used to determine impl visibility and reachability.
342struct FindMin<'a, 'tcx, VL: VisibilityLike, const SHALLOW: bool> {
343    tcx: TyCtxt<'tcx>,
344    effective_visibilities: &'a EffectiveVisibilities,
345    min: VL,
346}
347
348impl<'a, 'tcx, VL: VisibilityLike, const SHALLOW: bool> DefIdVisitor<'tcx>
349    for FindMin<'a, 'tcx, VL, SHALLOW>
350{
351    const SHALLOW: bool = SHALLOW;
352    fn skip_assoc_tys(&self) -> bool {
353        true
354    }
355    fn tcx(&self) -> TyCtxt<'tcx> {
356        self.tcx
357    }
358    fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) {
359        if let Some(def_id) = def_id.as_local() {
360            self.min = VL::new_min(self, def_id);
361        }
362    }
363}
364
365trait VisibilityLike: Sized {
366    const MAX: Self;
367    fn new_min<const SHALLOW: bool>(
368        find: &FindMin<'_, '_, Self, SHALLOW>,
369        def_id: LocalDefId,
370    ) -> Self;
371
372    // Returns an over-approximation (`skip_assoc_tys()` = true) of visibility due to
373    // associated types for which we can't determine visibility precisely.
374    fn of_impl<const SHALLOW: bool>(
375        def_id: LocalDefId,
376        of_trait: bool,
377        tcx: TyCtxt<'_>,
378        effective_visibilities: &EffectiveVisibilities,
379    ) -> Self {
380        let mut find = FindMin::<_, SHALLOW> { tcx, effective_visibilities, min: Self::MAX };
381        find.visit(tcx.type_of(def_id).instantiate_identity().skip_norm_wip());
382        if of_trait {
383            find.visit_trait(tcx.impl_trait_ref(def_id).instantiate_identity().skip_norm_wip());
384        }
385        find.min
386    }
387}
388
389impl VisibilityLike for ty::Visibility {
390    const MAX: Self = ty::Visibility::Public;
391    fn new_min<const SHALLOW: bool>(
392        find: &FindMin<'_, '_, Self, SHALLOW>,
393        def_id: LocalDefId,
394    ) -> Self {
395        min(find.tcx.local_visibility(def_id), find.min, find.tcx)
396    }
397}
398
399impl VisibilityLike for EffectiveVisibility {
400    const MAX: Self = EffectiveVisibility::from_vis(ty::Visibility::Public);
401    fn new_min<const SHALLOW: bool>(
402        find: &FindMin<'_, '_, Self, SHALLOW>,
403        def_id: LocalDefId,
404    ) -> Self {
405        let effective_vis =
406            find.effective_visibilities.effective_vis(def_id).copied().unwrap_or_else(|| {
407                let private_vis = ty::Visibility::Restricted(
408                    find.tcx.parent_module_from_def_id(def_id).to_local_def_id(),
409                );
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        // FIXME(typed_def_id): Make `Visibility::Restricted` use a `LocalModDefId` by default.
520        let private_vis =
521            ty::Visibility::Restricted(self.tcx.parent_module_from_def_id(def_id).into());
522        if max_vis != Some(private_vis) {
523            return self.effective_visibilities.update(
524                def_id,
525                max_vis,
526                private_vis,
527                inherited_effective_vis,
528                level,
529                self.tcx,
530            );
531        }
532        false
533    }
534
535    fn reach(
536        &mut self,
537        def_id: LocalDefId,
538        effective_vis: EffectiveVisibility,
539    ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
540        ReachEverythingInTheInterfaceVisitor {
541            effective_vis,
542            item_def_id: def_id,
543            ev: self,
544            level: Level::Reachable,
545        }
546    }
547
548    fn reach_through_impl_trait(
549        &mut self,
550        def_id: LocalDefId,
551        effective_vis: EffectiveVisibility,
552    ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
553        ReachEverythingInTheInterfaceVisitor {
554            effective_vis,
555            item_def_id: def_id,
556            ev: self,
557            level: Level::ReachableThroughImplTrait,
558        }
559    }
560}
561
562impl<'tcx> EmbargoVisitor<'tcx> {
563    fn check_assoc_item(&mut self, item: &ty::AssocItem, item_ev: EffectiveVisibility) {
564        let def_id = item.def_id.expect_local();
565        let tcx = self.tcx;
566        let mut reach = self.reach(def_id, item_ev);
567        reach.generics().predicates();
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 | DefKind::ExternCrate | DefKind::GlobalAsm => {}
584            // The interface is empty, and all nested items are processed by `check_def_id`.
585            DefKind::Mod => {}
586            // Effective visibilities for macros are processed earlier.
587            DefKind::Macro { .. } => {}
588            DefKind::ForeignTy
589            | DefKind::Const { .. }
590            | DefKind::Static { .. }
591            | DefKind::Fn
592            | DefKind::TyAlias => {
593                if let Some(item_ev) = item_ev {
594                    self.reach(def_id, item_ev).generics().predicates().ty();
595                }
596            }
597            DefKind::Trait => {
598                if let Some(item_ev) = item_ev {
599                    self.reach(def_id, item_ev).generics().predicates();
600
601                    for assoc_item in self.tcx.associated_items(def_id).in_definition_order() {
602                        let def_id = assoc_item.def_id.expect_local();
603                        self.update(def_id, item_ev, Level::Reachable);
604
605                        self.check_assoc_item(assoc_item, item_ev);
606                    }
607                }
608            }
609            DefKind::TraitAlias => {
610                if let Some(item_ev) = item_ev {
611                    self.reach(def_id, item_ev).generics().predicates();
612                }
613            }
614            DefKind::Impl { of_trait } => {
615                // Type inference is very smart sometimes. It can make an impl reachable even some
616                // components of its type or trait are unreachable. E.g. methods of
617                // `impl ReachableTrait<UnreachableTy> for ReachableTy<UnreachableTy> { ... }`
618                // can be usable from other crates (#57264). So we skip args when calculating
619                // reachability and consider an impl reachable if its "shallow" type and trait are
620                // reachable.
621                //
622                // The assumption we make here is that type-inference won't let you use an impl
623                // without knowing both "shallow" version of its self type and "shallow" version of
624                // its trait if it exists (which require reaching the `DefId`s in them).
625                let item_ev = EffectiveVisibility::of_impl::<true>(
626                    def_id,
627                    of_trait,
628                    self.tcx,
629                    &self.effective_visibilities,
630                );
631
632                self.update_eff_vis(def_id, item_ev, None, Level::Direct);
633
634                {
635                    let mut reach = self.reach(def_id, item_ev);
636                    reach.generics().predicates().ty();
637                    if of_trait {
638                        reach.trait_ref();
639                    }
640                }
641
642                for assoc_item in self.tcx.associated_items(def_id).in_definition_order() {
643                    let def_id = assoc_item.def_id.expect_local();
644                    let max_vis =
645                        if of_trait { None } else { Some(self.tcx.local_visibility(def_id)) };
646                    self.update_eff_vis(def_id, item_ev, max_vis, Level::Direct);
647
648                    if let Some(impl_item_ev) = self.get(def_id) {
649                        self.check_assoc_item(assoc_item, impl_item_ev);
650                    }
651                }
652            }
653            DefKind::Enum => {
654                if let Some(item_ev) = item_ev {
655                    self.reach(def_id, item_ev).generics().predicates();
656                }
657                let def = self.tcx.adt_def(def_id);
658                for variant in def.variants() {
659                    if let Some(item_ev) = item_ev {
660                        self.update(variant.def_id.expect_local(), item_ev, Level::Reachable);
661                    }
662
663                    if let Some(variant_ev) = self.get(variant.def_id.expect_local()) {
664                        if let Some(ctor_def_id) = variant.ctor_def_id() {
665                            self.update(ctor_def_id.expect_local(), variant_ev, Level::Reachable);
666                        }
667
668                        for field in &variant.fields {
669                            let field = field.did.expect_local();
670                            self.update(field, variant_ev, Level::Reachable);
671                            self.reach(field, variant_ev).ty();
672                        }
673                        // Corner case: if the variant is reachable, but its
674                        // enum is not, make the enum reachable as well.
675                        self.reach(def_id, variant_ev).ty();
676                    }
677                    if let Some(ctor_def_id) = variant.ctor_def_id() {
678                        if let Some(ctor_ev) = self.get(ctor_def_id.expect_local()) {
679                            self.reach(def_id, ctor_ev).ty();
680                        }
681                    }
682                }
683            }
684            DefKind::Struct | DefKind::Union => {
685                let def = self.tcx.adt_def(def_id).non_enum_variant();
686                if let Some(item_ev) = item_ev {
687                    self.reach(def_id, item_ev).generics().predicates();
688                    for field in &def.fields {
689                        let field = field.did.expect_local();
690                        self.update(field, item_ev, Level::Reachable);
691                        if let Some(field_ev) = self.get(field) {
692                            self.reach(field, field_ev).ty();
693                        }
694                    }
695                }
696                if let Some(ctor_def_id) = def.ctor_def_id() {
697                    if let Some(item_ev) = item_ev {
698                        self.update(ctor_def_id.expect_local(), item_ev, Level::Reachable);
699                    }
700                    if let Some(ctor_ev) = self.get(ctor_def_id.expect_local()) {
701                        self.reach(def_id, ctor_ev).ty();
702                    }
703                }
704            }
705            // Contents are checked directly.
706            DefKind::ForeignMod => {}
707            DefKind::Field
708            | DefKind::Variant
709            | DefKind::AssocFn
710            | DefKind::AssocTy
711            | DefKind::AssocConst { .. }
712            | DefKind::TyParam
713            | DefKind::AnonConst
714            | DefKind::InlineConst
715            | DefKind::OpaqueTy
716            | DefKind::Closure
717            | DefKind::SyntheticCoroutineBody
718            | DefKind::ConstParam
719            | DefKind::LifetimeParam
720            | DefKind::Ctor(..) => {
721                ::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!(
722                    self.tcx.def_span(def_id),
723                    "{def_kind:?} should be checked while checking parent"
724                )
725            }
726        }
727    }
728}
729
730impl ReachEverythingInTheInterfaceVisitor<'_, '_> {
731    fn generics(&mut self) -> &mut Self {
732        for param in &self.ev.tcx.generics_of(self.item_def_id).own_params {
733            if let GenericParamDefKind::Const { .. } = param.kind {
734                self.visit(
735                    self.ev.tcx.type_of(param.def_id).instantiate_identity().skip_norm_wip(),
736                );
737            }
738            if let Some(default) = param.default_value(self.ev.tcx) {
739                self.visit(default.instantiate_identity().skip_norm_wip());
740            }
741        }
742        self
743    }
744
745    fn predicates(&mut self) -> &mut Self {
746        self.visit_predicates(self.ev.tcx.explicit_predicates_of(self.item_def_id));
747        self
748    }
749
750    fn bounds(&mut self) -> &mut Self {
751        self.visit_clauses(self.ev.tcx.explicit_item_bounds(self.item_def_id).skip_binder());
752        self
753    }
754
755    fn ty(&mut self) -> &mut Self {
756        self.visit(self.ev.tcx.type_of(self.item_def_id).instantiate_identity().skip_norm_wip());
757        self
758    }
759
760    fn trait_ref(&mut self) -> &mut Self {
761        self.visit_trait(
762            self.ev.tcx.impl_trait_ref(self.item_def_id).instantiate_identity().skip_norm_wip(),
763        );
764        self
765    }
766
767    // If a def encountered in the interface is updated, we put those items
768    // that may be affected by this update into the queue.
769    fn enqueue_def_id(&mut self, def_id: LocalDefId) {
770        let def_kind = self.ev.tcx.def_kind(def_id);
771        match def_kind {
772            DefKind::Enum
773            | DefKind::Union
774            | DefKind::Struct
775            | DefKind::ForeignTy
776            | DefKind::Trait => {
777                self.ev.queue.insert(def_id);
778                // Make sure that all affected impls are traversed one more time.
779                if let Some(impls) = self.ev.def_ids_to_impls.get(&def_id) {
780                    // The order in which items are traversed is irrelevant.
781                    #[allow(rustc::potential_query_instability)]
782                    self.ev.queue.extend(impls);
783                }
784            }
785
786            DefKind::TraitAlias | DefKind::Fn | DefKind::TyAlias => {
787                self.ev.queue.insert(def_id);
788            }
789
790            DefKind::AssocConst { .. } | DefKind::AssocFn | DefKind::AssocTy => {
791                // Traverse the whole impl/trait.
792                self.ev.queue.insert(self.ev.tcx.local_parent(def_id));
793            }
794
795            DefKind::Ctor(ctor_of, _) => {
796                let update_id = match ctor_of {
797                    CtorOf::Struct => self.ev.tcx.local_parent(def_id),
798                    CtorOf::Variant => self.ev.tcx.local_parent(self.ev.tcx.local_parent(def_id)),
799                };
800                // Update the whole ADT.
801                self.ev.queue.insert(update_id);
802            }
803
804            // Can be reached via RPIT (impl Fn), but can't affect
805            // the effective visibility of other defs.
806            DefKind::Closure => {}
807
808            // Can't be reached
809            DefKind::Impl { .. }
810            | DefKind::Field
811            | DefKind::Variant
812            | DefKind::Static { .. }
813            | DefKind::Macro(_)
814            | DefKind::TyParam
815            | DefKind::AnonConst
816            | DefKind::InlineConst
817            | DefKind::OpaqueTy
818            | DefKind::SyntheticCoroutineBody
819            | DefKind::ConstParam
820            | DefKind::LifetimeParam
821            | DefKind::Mod
822            | DefKind::Use
823            | DefKind::ExternCrate
824            | DefKind::GlobalAsm
825            | DefKind::ForeignMod
826            | DefKind::Const { .. } => {
827                ::rustc_middle::util::bug::span_bug_fmt(self.tcx().def_span(def_id),
    format_args!("{0:?} unexpectedly reached by `ReachEverythingInTheInterfaceVisitor`",
        def_kind))span_bug!(
828                    self.tcx().def_span(def_id),
829                    "{def_kind:?} unexpectedly reached by `ReachEverythingInTheInterfaceVisitor`"
830                )
831            }
832        }
833    }
834}
835
836impl<'tcx> DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
837    fn tcx(&self) -> TyCtxt<'tcx> {
838        self.ev.tcx
839    }
840    fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) {
841        if let Some(def_id) = def_id.as_local() {
842            // All effective visibilities except `reachable_through_impl_trait` are limited to
843            // nominal visibility. If any type or trait is leaked farther than that, it will
844            // produce type privacy errors on any use, so we don't consider it leaked.
845            //
846            // FIXME: If self.level == Level::Reachable and self.ev == (priv, priv, priv, pub),
847            // then the effective visibility of def_id wouldn't be updated at level
848            // `ReachableThroughImplTrait` due to max_vis. Could this lead to a privacy violation?
849            let max_vis = (self.level != Level::ReachableThroughImplTrait)
850                .then(|| self.ev.tcx.local_visibility(def_id));
851            if self.ev.update_eff_vis(def_id, self.effective_vis, max_vis, self.level) {
852                self.enqueue_def_id(def_id);
853            }
854        }
855    }
856}
857
858/// Visitor, used for EffectiveVisibilities table checking
859pub struct TestReachabilityVisitor<'a, 'tcx> {
860    tcx: TyCtxt<'tcx>,
861    effective_visibilities: &'a EffectiveVisibilities,
862}
863
864impl<'a, 'tcx> TestReachabilityVisitor<'a, 'tcx> {
865    fn effective_visibility_diagnostic(&self, def_id: LocalDefId) {
866        if {
        {
            'done:
                {
                for i in
                    ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &self.tcx) {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(RustcEffectiveVisibility) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(self.tcx, def_id, RustcEffectiveVisibility) {
867            let mut error_msg = String::new();
868            let span = self.tcx.def_span(def_id.to_def_id());
869            if let Some(effective_vis) = self.effective_visibilities.effective_vis(def_id) {
870                for level in Level::all_levels() {
871                    let vis_str = effective_vis.at_level(level).to_string(def_id, self.tcx);
872                    if level != Level::Direct {
873                        error_msg.push_str(", ");
874                    }
875                    error_msg.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}: {1}", level, vis_str))
    })format!("{level:?}: {vis_str}"));
876                }
877            } else {
878                error_msg.push_str("not in the table");
879            }
880            self.tcx.dcx().emit_err(ReportEffectiveVisibility { span, descr: error_msg });
881        }
882    }
883}
884
885impl<'a, 'tcx> TestReachabilityVisitor<'a, 'tcx> {
886    fn check_def_id(&self, owner_id: OwnerId) {
887        self.effective_visibility_diagnostic(owner_id.def_id);
888
889        match self.tcx.def_kind(owner_id) {
890            DefKind::Enum => {
891                let def = self.tcx.adt_def(owner_id.def_id);
892                for variant in def.variants() {
893                    self.effective_visibility_diagnostic(variant.def_id.expect_local());
894                    if let Some(ctor_def_id) = variant.ctor_def_id() {
895                        self.effective_visibility_diagnostic(ctor_def_id.expect_local());
896                    }
897                    for field in &variant.fields {
898                        self.effective_visibility_diagnostic(field.did.expect_local());
899                    }
900                }
901            }
902            DefKind::Struct | DefKind::Union => {
903                let def = self.tcx.adt_def(owner_id.def_id).non_enum_variant();
904                if let Some(ctor_def_id) = def.ctor_def_id() {
905                    self.effective_visibility_diagnostic(ctor_def_id.expect_local());
906                }
907                for field in &def.fields {
908                    self.effective_visibility_diagnostic(field.did.expect_local());
909                }
910            }
911            _ => {}
912        }
913    }
914}
915
916/// Name privacy visitor, checks privacy and reports violations.
917///
918/// Most of name privacy checks are performed during the main resolution phase,
919/// or later in type checking when field accesses and associated items are resolved.
920/// This pass performs remaining checks for fields in struct expressions and patterns.
921struct NamePrivacyVisitor<'tcx> {
922    tcx: TyCtxt<'tcx>,
923    maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
924}
925
926impl<'tcx> NamePrivacyVisitor<'tcx> {
927    /// Gets the type-checking results for the current body.
928    /// As this will ICE if called outside bodies, only call when working with
929    /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
930    #[track_caller]
931    fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
932        self.maybe_typeck_results
933            .expect("`NamePrivacyVisitor::typeck_results` called outside of body")
934    }
935
936    // Checks that a field in a struct constructor (expression or pattern) is accessible.
937    fn check_field(
938        &self,
939        hir_id: hir::HirId,    // ID of the field use
940        use_ctxt: Span,        // syntax context of the field name at the use site
941        def: ty::AdtDef<'tcx>, // definition of the struct or enum
942        field: &'tcx ty::FieldDef,
943    ) -> bool {
944        if def.is_enum() {
945            return true;
946        }
947
948        // definition of the field
949        let ident = Ident::new(sym::dummy, use_ctxt);
950        let (_, def_id) = self.tcx.adjust_ident_and_get_scope(ident, def.did(), hir_id);
951        !field.vis.is_accessible_from(def_id, self.tcx)
952    }
953
954    // Checks that a field in a struct constructor (expression or pattern) is accessible.
955    fn emit_unreachable_field_error(
956        &self,
957        fields: Vec<(Symbol, Span, bool /* field is present */)>,
958        def: ty::AdtDef<'tcx>, // definition of the struct or enum
959        update_syntax: Option<Span>,
960        struct_span: Span,
961    ) {
962        if def.is_enum() || fields.is_empty() {
963            return;
964        }
965
966        //   error[E0451]: fields `beta` and `gamma` of struct `Alpha` are private
967        //   --> $DIR/visibility.rs:18:13
968        //    |
969        // LL |     let _x = Alpha {
970        //    |              ----- in this type      # from `def`
971        // LL |         beta: 0,
972        //    |         ^^^^^^^ private field        # `fields.2` is `true`
973        // LL |         ..
974        //    |         ^^ field `gamma` is private  # `fields.2` is `false`
975
976        // Get the list of all private fields for the main message.
977        let Some(field_names) = listify(&fields[..], |(n, _, _)| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", n))
    })format!("`{n}`")) else { return };
978        let span: MultiSpan = fields.iter().map(|(_, span, _)| *span).collect::<Vec<Span>>().into();
979
980        // Get the list of all private fields when pointing at the `..rest`.
981        let rest_field_names: Vec<_> =
982            fields.iter().filter(|(_, _, is_present)| !is_present).map(|(n, _, _)| n).collect();
983        let rest_len = rest_field_names.len();
984        let rest_field_names =
985            listify(&rest_field_names[..], |n| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", n))
    })format!("`{n}`")).unwrap_or_default();
986        // Get all the labels for each field or `..rest` in the primary MultiSpan.
987        let labels = fields
988            .iter()
989            .filter(|(_, _, is_present)| *is_present)
990            .map(|(_, span, _)| FieldIsPrivateLabel::Other { span: *span })
991            .chain(update_syntax.iter().map(|span| FieldIsPrivateLabel::IsUpdateSyntax {
992                span: *span,
993                rest_field_names: rest_field_names.clone(),
994                rest_len,
995            }))
996            .collect();
997
998        self.tcx.dcx().emit_err(FieldIsPrivate {
999            span,
1000            struct_span: if self
1001                .tcx
1002                .sess
1003                .source_map()
1004                .is_multiline(fields[0].1.between(struct_span))
1005            {
1006                Some(struct_span)
1007            } else {
1008                None
1009            },
1010            field_names,
1011            variant_descr: def.variant_descr(),
1012            def_path_str: self.tcx.def_path_str(def.did()),
1013            labels,
1014            len: fields.len(),
1015        });
1016    }
1017
1018    fn check_expanded_fields(
1019        &self,
1020        adt: ty::AdtDef<'tcx>,
1021        variant: &'tcx ty::VariantDef,
1022        fields: &[hir::ExprField<'tcx>],
1023        hir_id: hir::HirId,
1024        span: Span,
1025        struct_span: Span,
1026    ) {
1027        let mut failed_fields = ::alloc::vec::Vec::new()vec![];
1028        for (vf_index, variant_field) in variant.fields.iter_enumerated() {
1029            let field =
1030                fields.iter().find(|f| self.typeck_results().field_index(f.hir_id) == vf_index);
1031            let (hir_id, use_ctxt, span) = match field {
1032                Some(field) => (field.hir_id, field.ident.span, field.span),
1033                None => (hir_id, span, span),
1034            };
1035            if self.check_field(hir_id, use_ctxt, adt, variant_field) {
1036                let name = match field {
1037                    Some(field) => field.ident.name,
1038                    None => variant_field.name,
1039                };
1040                failed_fields.push((name, span, field.is_some()));
1041            }
1042        }
1043        self.emit_unreachable_field_error(failed_fields, adt, Some(span), struct_span);
1044    }
1045}
1046
1047impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> {
1048    fn visit_nested_body(&mut self, body_id: hir::BodyId) {
1049        let new_typeck_results = self.tcx.typeck_body(body_id);
1050        // Do not try reporting privacy violations if we failed to infer types.
1051        if new_typeck_results.tainted_by_errors.is_some() {
1052            return;
1053        }
1054        let old_maybe_typeck_results = self.maybe_typeck_results.replace(new_typeck_results);
1055        self.visit_body(self.tcx.hir_body(body_id));
1056        self.maybe_typeck_results = old_maybe_typeck_results;
1057    }
1058
1059    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1060        if let hir::ExprKind::Struct(qpath, fields, ref base) = expr.kind {
1061            let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
1062            let adt = self.typeck_results().expr_ty(expr).ty_adt_def().unwrap();
1063            let variant = adt.variant_of_res(res);
1064            match *base {
1065                hir::StructTailExpr::Base(base) => {
1066                    // If the expression uses FRU we need to make sure all the unmentioned fields
1067                    // are checked for privacy (RFC 736). Rather than computing the set of
1068                    // unmentioned fields, just check them all.
1069                    self.check_expanded_fields(
1070                        adt,
1071                        variant,
1072                        fields,
1073                        base.hir_id,
1074                        base.span,
1075                        qpath.span(),
1076                    );
1077                }
1078                hir::StructTailExpr::DefaultFields(span) => {
1079                    self.check_expanded_fields(
1080                        adt,
1081                        variant,
1082                        fields,
1083                        expr.hir_id,
1084                        span,
1085                        qpath.span(),
1086                    );
1087                }
1088                hir::StructTailExpr::None | hir::StructTailExpr::NoneWithError(_) => {
1089                    let mut failed_fields = ::alloc::vec::Vec::new()vec![];
1090                    for field in fields {
1091                        let (hir_id, use_ctxt) = (field.hir_id, field.ident.span);
1092                        let index = self.typeck_results().field_index(field.hir_id);
1093                        if self.check_field(hir_id, use_ctxt, adt, &variant.fields[index]) {
1094                            failed_fields.push((field.ident.name, field.ident.span, true));
1095                        }
1096                    }
1097                    self.emit_unreachable_field_error(failed_fields, adt, None, qpath.span());
1098                }
1099            }
1100        }
1101
1102        intravisit::walk_expr(self, expr);
1103    }
1104
1105    fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) {
1106        if let PatKind::Struct(ref qpath, fields, _) = pat.kind {
1107            let res = self.typeck_results().qpath_res(qpath, pat.hir_id);
1108            let adt = self.typeck_results().pat_ty(pat).ty_adt_def().unwrap();
1109            let variant = adt.variant_of_res(res);
1110            let mut failed_fields = ::alloc::vec::Vec::new()vec![];
1111            for field in fields {
1112                let (hir_id, use_ctxt) = (field.hir_id, field.ident.span);
1113                let index = self.typeck_results().field_index(field.hir_id);
1114                if self.check_field(hir_id, use_ctxt, adt, &variant.fields[index]) {
1115                    failed_fields.push((field.ident.name, field.ident.span, true));
1116                }
1117            }
1118            self.emit_unreachable_field_error(failed_fields, adt, None, qpath.span());
1119        }
1120
1121        intravisit::walk_pat(self, pat);
1122    }
1123}
1124
1125/// Type privacy visitor, checks types for privacy and reports violations.
1126///
1127/// Both explicitly written types and inferred types of expressions and patterns are checked.
1128/// Checks are performed on "semantic" types regardless of names and their hygiene.
1129struct TypePrivacyVisitor<'tcx> {
1130    tcx: TyCtxt<'tcx>,
1131    module_def_id: LocalModDefId,
1132    maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
1133    span: Span,
1134}
1135
1136impl<'tcx> TypePrivacyVisitor<'tcx> {
1137    fn item_is_accessible(&self, did: DefId) -> bool {
1138        self.tcx.visibility(did).is_accessible_from(self.module_def_id, self.tcx)
1139    }
1140
1141    // Take node-id of an expression or pattern and check its type for privacy.
1142    fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool {
1143        self.span = span;
1144        let typeck_results = self
1145            .maybe_typeck_results
1146            .unwrap_or_else(|| ::rustc_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"));
1147        try {
1148            self.visit(typeck_results.node_type(id))?;
1149            self.visit(typeck_results.node_args(id))?;
1150            if let Some(adjustments) = typeck_results.adjustments().get(id) {
1151                adjustments.iter().try_for_each(|adjustment| self.visit(adjustment.target))?;
1152            }
1153        }
1154        .is_break()
1155    }
1156
1157    fn check_def_id(&self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool {
1158        let is_error = !self.item_is_accessible(def_id);
1159        if is_error {
1160            self.tcx.dcx().emit_err(ItemIsPrivate { span: self.span, kind, descr: descr.into() });
1161        }
1162        is_error
1163    }
1164}
1165
1166impl<'tcx> rustc_ty_utils::sig_types::SpannedTypeVisitor<'tcx> for TypePrivacyVisitor<'tcx> {
1167    type Result = ControlFlow<()>;
1168    fn visit(&mut self, span: Span, value: impl TypeVisitable<TyCtxt<'tcx>>) -> Self::Result {
1169        self.span = span;
1170        value.visit_with(&mut self.skeleton())
1171    }
1172}
1173
1174impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> {
1175    fn visit_nested_body(&mut self, body_id: hir::BodyId) {
1176        let old_maybe_typeck_results =
1177            self.maybe_typeck_results.replace(self.tcx.typeck_body(body_id));
1178        self.visit_body(self.tcx.hir_body(body_id));
1179        self.maybe_typeck_results = old_maybe_typeck_results;
1180    }
1181
1182    fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx, AmbigArg>) {
1183        self.span = hir_ty.span;
1184        if self
1185            .visit(
1186                self.maybe_typeck_results
1187                    .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"))
1188                    .node_type(hir_ty.hir_id),
1189            )
1190            .is_break()
1191        {
1192            return;
1193        }
1194
1195        intravisit::walk_ty(self, hir_ty);
1196    }
1197
1198    fn visit_infer(
1199        &mut self,
1200        inf_id: rustc_hir::HirId,
1201        inf_span: Span,
1202        _kind: InferKind<'tcx>,
1203    ) -> Self::Result {
1204        self.span = inf_span;
1205        if let Some(ty) = self
1206            .maybe_typeck_results
1207            .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"))
1208            .node_type_opt(inf_id)
1209        {
1210            if self.visit(ty).is_break() {
1211                return;
1212            }
1213        } else {
1214            // FIXME: check types of const infers here.
1215        }
1216
1217        self.visit_id(inf_id)
1218    }
1219
1220    // Check types of expressions
1221    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
1222        if self.check_expr_pat_type(expr.hir_id, expr.span) {
1223            // Do not check nested expressions if the error already happened.
1224            return;
1225        }
1226        match expr.kind {
1227            hir::ExprKind::Assign(_, rhs, _) | hir::ExprKind::Match(rhs, ..) => {
1228                // Do not report duplicate errors for `x = y` and `match x { ... }`.
1229                if self.check_expr_pat_type(rhs.hir_id, rhs.span) {
1230                    return;
1231                }
1232            }
1233            hir::ExprKind::MethodCall(segment, ..) => {
1234                // Method calls have to be checked specially.
1235                self.span = segment.ident.span;
1236                let typeck_results = self
1237                    .maybe_typeck_results
1238                    .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"));
1239                if let Some(def_id) = typeck_results.type_dependent_def_id(expr.hir_id) {
1240                    if self
1241                        .visit(self.tcx.type_of(def_id).instantiate_identity().skip_norm_wip())
1242                        .is_break()
1243                    {
1244                        return;
1245                    }
1246                } else {
1247                    self.tcx
1248                        .dcx()
1249                        .span_delayed_bug(expr.span, "no type-dependent def for method call");
1250                }
1251            }
1252            _ => {}
1253        }
1254
1255        intravisit::walk_expr(self, expr);
1256    }
1257
1258    // Prohibit access to associated items with insufficient nominal visibility.
1259    //
1260    // Additionally, until better reachability analysis for macros 2.0 is available,
1261    // we prohibit access to private statics from other crates, this allows to give
1262    // more code internal visibility at link time. (Access to private functions
1263    // is already prohibited by type privacy for function types.)
1264    fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) {
1265        let def = match qpath {
1266            hir::QPath::Resolved(_, path) => match path.res {
1267                Res::Def(kind, def_id) => Some((kind, def_id)),
1268                _ => None,
1269            },
1270            hir::QPath::TypeRelative(..) => {
1271                match self.maybe_typeck_results {
1272                    Some(typeck_results) => typeck_results.type_dependent_def(id),
1273                    // FIXME: Check type-relative associated types in signatures.
1274                    None => None,
1275                }
1276            }
1277        };
1278        let def = def.filter(|(kind, _)| {
1279            #[allow(non_exhaustive_omitted_patterns)] match kind {
    DefKind::AssocFn | DefKind::AssocConst { .. } | DefKind::AssocTy |
        DefKind::Static { .. } => true,
    _ => false,
}matches!(
1280                kind,
1281                DefKind::AssocFn
1282                    | DefKind::AssocConst { .. }
1283                    | DefKind::AssocTy
1284                    | 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 predicates(&mut self) -> &mut Self {
1383        self.in_primary_interface = false;
1384        // N.B., we use `explicit_predicates_of` and not `predicates_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_predicates(self.tcx.explicit_predicates_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                lint::builtin::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_def_id) => {
1438                    if vis_def_id
1439                        == self.tcx.parent_module_from_def_id(local_def_id).to_local_def_id()
1440                    {
1441                        "private"
1442                    } else if vis_def_id.is_top_level_module() {
1443                        "crate-private"
1444                    } else {
1445                        "restricted"
1446                    }
1447                }
1448            };
1449
1450            let span = self.tcx.def_span(self.item_def_id.to_def_id());
1451            let vis_span = self.tcx.def_span(def_id);
1452            self.tcx.dcx().emit_err(InPublicInterface {
1453                span,
1454                vis_descr,
1455                kind,
1456                descr: descr.into(),
1457                vis_span,
1458            });
1459            return false;
1460        }
1461
1462        let Some(effective_vis) = self.required_effective_vis else {
1463            return false;
1464        };
1465
1466        let reachable_at_vis = *effective_vis.at_level(Level::Reachable);
1467
1468        if reachable_at_vis.greater_than(vis, self.tcx) {
1469            let lint = if self.in_primary_interface {
1470                lint::builtin::PRIVATE_INTERFACES
1471            } else {
1472                lint::builtin::PRIVATE_BOUNDS
1473            };
1474            let span = self.tcx.def_span(self.item_def_id.to_def_id());
1475            let vis_span = self.tcx.def_span(def_id);
1476            self.tcx.emit_node_span_lint(
1477                lint,
1478                self.tcx.local_def_id_to_hir_id(self.item_def_id),
1479                span,
1480                PrivateInterfacesOrBoundsLint {
1481                    item_span: span,
1482                    item_kind: self.tcx.def_descr(self.item_def_id.to_def_id()),
1483                    item_descr: (&LazyDefPathStr {
1484                        def_id: self.item_def_id.to_def_id(),
1485                        tcx: self.tcx,
1486                    })
1487                        .into(),
1488                    item_vis_descr: &reachable_at_vis.to_string(self.item_def_id, self.tcx),
1489                    ty_span: vis_span,
1490                    ty_kind: kind,
1491                    ty_descr: descr.into(),
1492                    ty_vis_descr: &vis.to_string(local_def_id, self.tcx),
1493                },
1494            );
1495        }
1496
1497        false
1498    }
1499
1500    /// An item is 'leaked' from a private dependency if all
1501    /// of the following are true:
1502    /// 1. It's contained within a public type
1503    /// 2. It comes from a private crate
1504    fn leaks_private_dep(&self, item_id: DefId) -> bool {
1505        let ret = self.required_visibility.is_public() && self.tcx.is_private_dep(item_id.krate);
1506
1507        {
    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:1507",
                        "rustc_privacy", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_privacy/src/lib.rs"),
                        ::tracing_core::__macro_support::Option::Some(1507u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_privacy"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("leaks_private_dep(item_id={0:?})={1}",
                                                    item_id, ret) as &dyn Value))])
            });
    } else { ; }
};debug!("leaks_private_dep(item_id={:?})={}", item_id, ret);
1508        ret
1509    }
1510}
1511
1512impl<'tcx> DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> {
1513    type Result = ControlFlow<()>;
1514    fn skip_assoc_tys(&self) -> bool {
1515        self.skip_assoc_tys
1516    }
1517    fn tcx(&self) -> TyCtxt<'tcx> {
1518        self.tcx
1519    }
1520    fn visit_def_id(
1521        &mut self,
1522        def_id: DefId,
1523        kind: &str,
1524        descr: &dyn fmt::Display,
1525    ) -> Self::Result {
1526        if self.check_def_id(def_id, kind, descr) {
1527            ControlFlow::Break(())
1528        } else {
1529            ControlFlow::Continue(())
1530        }
1531    }
1532}
1533
1534struct PrivateItemsInPublicInterfacesChecker<'a, 'tcx> {
1535    tcx: TyCtxt<'tcx>,
1536    effective_visibilities: &'a EffectiveVisibilities,
1537}
1538
1539impl<'tcx> PrivateItemsInPublicInterfacesChecker<'_, 'tcx> {
1540    fn check(
1541        &self,
1542        def_id: LocalDefId,
1543        required_visibility: ty::Visibility,
1544        required_effective_vis: Option<EffectiveVisibility>,
1545    ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> {
1546        SearchInterfaceForPrivateItemsVisitor {
1547            tcx: self.tcx,
1548            item_def_id: def_id,
1549            required_visibility,
1550            required_effective_vis,
1551            ..
1552        }
1553    }
1554
1555    fn check_unnameable(&self, def_id: LocalDefId, effective_vis: Option<EffectiveVisibility>) {
1556        let Some(effective_vis) = effective_vis else {
1557            return;
1558        };
1559
1560        let reexported_at_vis = effective_vis.at_level(Level::Reexported);
1561        let reachable_at_vis = effective_vis.at_level(Level::Reachable);
1562
1563        if reachable_at_vis.is_public() && reexported_at_vis != reachable_at_vis {
1564            let hir_id = self.tcx.local_def_id_to_hir_id(def_id);
1565            let span = self.tcx.def_span(def_id.to_def_id());
1566            self.tcx.emit_node_span_lint(
1567                lint::builtin::UNNAMEABLE_TYPES,
1568                hir_id,
1569                span,
1570                UnnameableTypesLint {
1571                    span,
1572                    kind: self.tcx.def_descr(def_id.to_def_id()),
1573                    descr: (&LazyDefPathStr { def_id: def_id.to_def_id(), tcx: self.tcx }).into(),
1574                    reachable_vis: &reachable_at_vis.to_string(def_id, self.tcx),
1575                    reexported_vis: &reexported_at_vis.to_string(def_id, self.tcx),
1576                },
1577            );
1578        }
1579    }
1580
1581    fn check_assoc_item(
1582        &self,
1583        item: &ty::AssocItem,
1584        vis: ty::Visibility,
1585        effective_vis: Option<EffectiveVisibility>,
1586    ) {
1587        let mut check = self.check(item.def_id.expect_local(), vis, effective_vis);
1588
1589        let is_assoc_ty = item.is_type();
1590        check.hard_error = is_assoc_ty;
1591        check.generics().predicates();
1592        if assoc_has_type_of(self.tcx, item) {
1593            check.ty();
1594        }
1595        if is_assoc_ty && item.container == AssocContainer::Trait {
1596            // FIXME: too much breakage from reporting hard errors here, better wait for a fix
1597            // from proper associated type normalization.
1598            check.hard_error = false;
1599            check.bounds();
1600        }
1601    }
1602
1603    fn get(&self, def_id: LocalDefId) -> Option<EffectiveVisibility> {
1604        self.effective_visibilities.effective_vis(def_id).copied()
1605    }
1606
1607    fn check_item(&self, id: ItemId) {
1608        let tcx = self.tcx;
1609        let def_id = id.owner_id.def_id;
1610        let item_visibility = tcx.local_visibility(def_id);
1611        let effective_vis = self.get(def_id);
1612        let def_kind = tcx.def_kind(def_id);
1613
1614        match def_kind {
1615            DefKind::Const { .. } | DefKind::Static { .. } | DefKind::Fn | DefKind::TyAlias => {
1616                if let DefKind::TyAlias = def_kind {
1617                    self.check_unnameable(def_id, effective_vis);
1618                }
1619                self.check(def_id, item_visibility, effective_vis).generics().predicates().ty();
1620            }
1621            DefKind::OpaqueTy => {
1622                // `ty()` for opaque types is the underlying type,
1623                // it's not a part of interface, so we skip it.
1624                self.check(def_id, item_visibility, effective_vis).generics().bounds();
1625            }
1626            DefKind::Trait => {
1627                self.check_unnameable(def_id, effective_vis);
1628
1629                self.check(def_id, item_visibility, effective_vis).generics().predicates();
1630
1631                for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() {
1632                    self.check_assoc_item(assoc_item, item_visibility, effective_vis);
1633                }
1634            }
1635            DefKind::TraitAlias => {
1636                self.check(def_id, item_visibility, effective_vis).generics().predicates();
1637            }
1638            DefKind::Enum => {
1639                self.check_unnameable(def_id, effective_vis);
1640                self.check(def_id, item_visibility, effective_vis).generics().predicates();
1641
1642                let adt = tcx.adt_def(id.owner_id);
1643                for field in adt.all_fields() {
1644                    self.check(field.did.expect_local(), item_visibility, effective_vis).ty();
1645                }
1646            }
1647            // Subitems of structs and unions have their own publicity.
1648            DefKind::Struct | DefKind::Union => {
1649                self.check_unnameable(def_id, effective_vis);
1650                self.check(def_id, item_visibility, effective_vis).generics().predicates();
1651
1652                let adt = tcx.adt_def(id.owner_id);
1653                for field in adt.all_fields() {
1654                    let visibility = min(item_visibility, field.vis.expect_local(), tcx);
1655                    let field_ev = self.get(field.did.expect_local());
1656
1657                    self.check(field.did.expect_local(), visibility, field_ev).ty();
1658                }
1659            }
1660            // Subitems of foreign modules have their own publicity.
1661            DefKind::ForeignMod => {}
1662            // An inherent impl is public when its type is public
1663            // Subitems of inherent impls have their own publicity.
1664            // A trait impl is public when both its type and its trait are public
1665            // Subitems of trait impls have inherited publicity.
1666            DefKind::Impl { of_trait } => {
1667                let impl_vis =
1668                    ty::Visibility::of_impl::<false>(def_id, of_trait, tcx, &Default::default());
1669
1670                // We are using the non-shallow version here, unlike when building the
1671                // effective visisibilities table to avoid large number of false positives.
1672                // For example in
1673                //
1674                // impl From<Priv> for Pub {
1675                //     fn from(_: Priv) -> Pub {...}
1676                // }
1677                //
1678                // lints shouldn't be emitted even if `from` effective visibility
1679                // is larger than `Priv` nominal visibility and if `Priv` can leak
1680                // in some scenarios due to type inference.
1681                let impl_ev = EffectiveVisibility::of_impl::<false>(
1682                    def_id,
1683                    of_trait,
1684                    tcx,
1685                    self.effective_visibilities,
1686                );
1687
1688                let mut check = self.check(def_id, impl_vis, Some(impl_ev));
1689
1690                // Generics and predicates of trait impls are intentionally not checked
1691                // for private components (#90586).
1692                if !of_trait {
1693                    check.generics().predicates();
1694                }
1695
1696                // Skip checking private components in associated types, due to lack of full
1697                // normalization they produce very ridiculous false positives.
1698                // FIXME: Remove this when full normalization is implemented.
1699                check.skip_assoc_tys = true;
1700                check.ty();
1701                if of_trait {
1702                    check.trait_ref();
1703                }
1704
1705                for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() {
1706                    let impl_item_vis = if !of_trait {
1707                        min(tcx.local_visibility(assoc_item.def_id.expect_local()), impl_vis, tcx)
1708                    } else {
1709                        impl_vis
1710                    };
1711
1712                    let impl_item_ev = if !of_trait {
1713                        self.get(assoc_item.def_id.expect_local())
1714                            .map(|ev| ev.min(impl_ev, self.tcx))
1715                    } else {
1716                        Some(impl_ev)
1717                    };
1718
1719                    self.check_assoc_item(assoc_item, impl_item_vis, impl_item_ev);
1720                }
1721            }
1722            _ => {}
1723        }
1724    }
1725
1726    fn check_foreign_item(&self, id: ForeignItemId) {
1727        let tcx = self.tcx;
1728        let def_id = id.owner_id.def_id;
1729        let item_visibility = tcx.local_visibility(def_id);
1730        let effective_vis = self.get(def_id);
1731
1732        if let DefKind::ForeignTy = self.tcx.def_kind(def_id) {
1733            self.check_unnameable(def_id, effective_vis);
1734        }
1735
1736        self.check(def_id, item_visibility, effective_vis).generics().predicates().ty();
1737    }
1738}
1739
1740pub fn provide(providers: &mut Providers) {
1741    *providers = Providers {
1742        effective_visibilities,
1743        check_private_in_public,
1744        check_mod_privacy,
1745        ..*providers
1746    };
1747}
1748
1749fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
1750    // Check privacy of names not checked in previous compilation stages.
1751    let mut visitor = NamePrivacyVisitor { tcx, maybe_typeck_results: None };
1752    tcx.hir_visit_item_likes_in_module(module_def_id, &mut visitor);
1753
1754    // Check privacy of explicitly written types and traits as well as
1755    // inferred types of expressions and patterns.
1756    let span = tcx.def_span(module_def_id);
1757    let mut visitor = TypePrivacyVisitor { tcx, module_def_id, maybe_typeck_results: None, span };
1758
1759    let module = tcx.hir_module_items(module_def_id);
1760    for def_id in module.definitions() {
1761        let _ = rustc_ty_utils::sig_types::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
1833                    .reach_through_impl_trait(opaque.def_id, pub_ev)
1834                    .generics()
1835                    .predicates()
1836                    .ty();
1837            }
1838        }
1839
1840        visitor.queue.clear();
1841    }
1842
1843    // FIXME: remove this once proper support for defs reachability from macros is implemented.
1844    // See `ResolverGlobalCtxt::macro_reachable_adts` comment.
1845    for (&adt_def_id, macro_mods) in &tcx.resolutions(()).macro_reachable_adts {
1846        let struct_def = tcx.adt_def(adt_def_id);
1847        let Some(struct_ev) = visitor.effective_visibilities.effective_vis(adt_def_id).copied()
1848        else {
1849            continue;
1850        };
1851        for field in &struct_def.non_enum_variant().fields {
1852            let def_id = field.did.expect_local();
1853            let field_vis = tcx.local_visibility(def_id);
1854
1855            for &macro_mod in macro_mods {
1856                if field_vis.is_accessible_from(macro_mod, tcx) {
1857                    visitor.reach(def_id, struct_ev).ty();
1858                }
1859            }
1860        }
1861    }
1862
1863    let crate_items = tcx.hir_crate_items(());
1864    for id in crate_items.free_items() {
1865        visitor.check_def_id(id.owner_id.def_id);
1866    }
1867    for id in crate_items.foreign_items() {
1868        visitor.check_def_id(id.owner_id.def_id);
1869    }
1870    while let Some(def_id) = visitor.queue.pop() {
1871        visitor.check_def_id(def_id);
1872    }
1873    visitor.effective_visibilities.check_invariants(tcx);
1874
1875    let check_visitor =
1876        TestReachabilityVisitor { tcx, effective_visibilities: &visitor.effective_visibilities };
1877    for id in crate_items.owners() {
1878        check_visitor.check_def_id(id);
1879    }
1880
1881    tcx.arena.alloc(visitor.effective_visibilities)
1882}
1883
1884fn check_private_in_public(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
1885    let effective_visibilities = tcx.effective_visibilities(());
1886    // Check for private types in public interfaces.
1887    let checker = PrivateItemsInPublicInterfacesChecker { tcx, effective_visibilities };
1888
1889    let crate_items = tcx.hir_module_items(module_def_id);
1890    let _ = crate_items.par_items(|id| Ok(checker.check_item(id)));
1891    let _ = crate_items.par_foreign_items(|id| Ok(checker.check_foreign_item(id)));
1892}