Skip to main content

rustc_middle/middle/
privacy.rs

1//! A pass that checks to make sure private fields and methods aren't used
2//! outside their scopes. This pass will also generate a set of exported items
3//! which are available for use externally when compiled as a library.
4
5use std::cmp::Ordering;
6use std::hash::Hash;
7
8use rustc_data_structures::fx::{FxIndexMap, IndexEntry};
9use rustc_data_structures::stable_hasher::{StableHash, StableHashCtxt, StableHasher};
10use rustc_hir::def::DefKind;
11use rustc_hir::{ItemKind, Node, UseKind};
12use rustc_macros::StableHash;
13use rustc_span::def_id::{CRATE_DEF_ID, LocalDefId};
14
15use crate::ty::{TyCtxt, Visibility};
16
17/// Represents the levels of effective visibility an item can have.
18///
19/// The variants are sorted in ascending order of directness.
20#[derive(#[automatically_derived]
impl ::core::clone::Clone for Level {
    #[inline]
    fn clone(&self) -> Level { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Level { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Level {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                Level::ReachableThroughImplTrait =>
                    "ReachableThroughImplTrait",
                Level::Reachable => "Reachable",
                Level::Reexported => "Reexported",
                Level::Direct => "Direct",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for Level {
    #[inline]
    fn eq(&self, other: &Level) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Level {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for Level {
    #[inline]
    fn partial_cmp(&self, other: &Level)
        -> ::core::option::Option<::core::cmp::Ordering> {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        ::core::cmp::PartialOrd::partial_cmp(&__self_discr, &__arg1_discr)
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for Level {
    #[inline]
    fn cmp(&self, other: &Level) -> ::core::cmp::Ordering {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        ::core::cmp::Ord::cmp(&__self_discr, &__arg1_discr)
    }
}Ord, const _: () =
    {
        impl ::rustc_data_structures::stable_hasher::StableHash for Level {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hasher::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    Level::ReachableThroughImplTrait => {}
                    Level::Reachable => {}
                    Level::Reexported => {}
                    Level::Direct => {}
                }
            }
        }
    };StableHash)]
21pub enum Level {
22    /// Superset of `Reachable` including items leaked through return position `impl Trait`.
23    ReachableThroughImplTrait,
24    /// Item is either reexported, or leaked through any kind of interface.
25    /// For example, if function `fn f() -> T {...}` is directly public, then type `T` is publicly
26    /// reachable and its values can be obtained by other crates even if the type itself is not
27    /// nameable.
28    Reachable,
29    /// Item is accessible either directly, or with help of `use` reexports.
30    Reexported,
31    /// Item is directly accessible, without help of reexports.
32    Direct,
33}
34
35impl Level {
36    pub fn all_levels() -> [Level; 4] {
37        [Level::Direct, Level::Reexported, Level::Reachable, Level::ReachableThroughImplTrait]
38    }
39}
40
41#[derive(#[automatically_derived]
impl ::core::clone::Clone for EffectiveVisibility {
    #[inline]
    fn clone(&self) -> EffectiveVisibility {
        let _: ::core::clone::AssertParamIsClone<Visibility>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for EffectiveVisibility { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for EffectiveVisibility {
    #[inline]
    fn eq(&self, other: &EffectiveVisibility) -> bool {
        self.direct == other.direct && self.reexported == other.reexported &&
                self.reachable == other.reachable &&
            self.reachable_through_impl_trait ==
                other.reachable_through_impl_trait
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for EffectiveVisibility {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Visibility>;
    }
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for EffectiveVisibility {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "EffectiveVisibility", "direct", &self.direct, "reexported",
            &self.reexported, "reachable", &self.reachable,
            "reachable_through_impl_trait",
            &&self.reachable_through_impl_trait)
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hasher::StableHash for
            EffectiveVisibility {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hasher::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                match *self {
                    EffectiveVisibility {
                        direct: ref __binding_0,
                        reexported: ref __binding_1,
                        reachable: ref __binding_2,
                        reachable_through_impl_trait: ref __binding_3 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                        { __binding_3.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
42pub struct EffectiveVisibility {
43    direct: Visibility,
44    reexported: Visibility,
45    reachable: Visibility,
46    reachable_through_impl_trait: Visibility,
47}
48
49impl EffectiveVisibility {
50    pub fn at_level(&self, level: Level) -> &Visibility {
51        match level {
52            Level::Direct => &self.direct,
53            Level::Reexported => &self.reexported,
54            Level::Reachable => &self.reachable,
55            Level::ReachableThroughImplTrait => &self.reachable_through_impl_trait,
56        }
57    }
58
59    fn at_level_mut(&mut self, level: Level) -> &mut Visibility {
60        match level {
61            Level::Direct => &mut self.direct,
62            Level::Reexported => &mut self.reexported,
63            Level::Reachable => &mut self.reachable,
64            Level::ReachableThroughImplTrait => &mut self.reachable_through_impl_trait,
65        }
66    }
67
68    pub fn is_public_at_level(&self, level: Level) -> bool {
69        self.at_level(level).is_public()
70    }
71
72    pub const fn from_vis(vis: Visibility) -> EffectiveVisibility {
73        EffectiveVisibility {
74            direct: vis,
75            reexported: vis,
76            reachable: vis,
77            reachable_through_impl_trait: vis,
78        }
79    }
80
81    #[must_use]
82    pub fn min(mut self, lhs: EffectiveVisibility, tcx: TyCtxt<'_>) -> Self {
83        for l in Level::all_levels() {
84            let rhs_vis = self.at_level_mut(l);
85            let lhs_vis = *lhs.at_level(l);
86            // FIXME: figure out why unordered visibilities occur here,
87            // and what the behavior for them should be.
88            if rhs_vis.partial_cmp(lhs_vis, tcx) == Some(Ordering::Greater) {
89                *rhs_vis = lhs_vis;
90            };
91        }
92        self
93    }
94}
95
96/// Holds a map of effective visibilities for reachable HIR nodes.
97#[derive(#[automatically_derived]
impl<Id: ::core::clone::Clone> ::core::clone::Clone for
    EffectiveVisibilities<Id> {
    #[inline]
    fn clone(&self) -> EffectiveVisibilities<Id> {
        EffectiveVisibilities { map: ::core::clone::Clone::clone(&self.map) }
    }
}Clone, #[automatically_derived]
impl<Id: ::core::fmt::Debug> ::core::fmt::Debug for EffectiveVisibilities<Id>
    {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "EffectiveVisibilities", "map", &&self.map)
    }
}Debug)]
98pub struct EffectiveVisibilities<Id = LocalDefId> {
99    map: FxIndexMap<Id, EffectiveVisibility>,
100}
101
102impl EffectiveVisibilities {
103    pub fn is_public_at_level(&self, id: LocalDefId, level: Level) -> bool {
104        self.effective_vis(id).is_some_and(|effective_vis| effective_vis.is_public_at_level(level))
105    }
106
107    /// See `Level::Reachable`.
108    pub fn is_reachable(&self, id: LocalDefId) -> bool {
109        self.is_public_at_level(id, Level::Reachable)
110    }
111
112    /// See `Level::Reexported`.
113    pub fn is_exported(&self, id: LocalDefId) -> bool {
114        self.is_public_at_level(id, Level::Reexported)
115    }
116
117    /// See `Level::Direct`.
118    pub fn is_directly_public(&self, id: LocalDefId) -> bool {
119        self.is_public_at_level(id, Level::Direct)
120    }
121
122    pub fn public_at_level(&self, id: LocalDefId) -> Option<Level> {
123        self.effective_vis(id).and_then(|effective_vis| {
124            Level::all_levels().into_iter().find(|&level| effective_vis.is_public_at_level(level))
125        })
126    }
127
128    pub fn update_root(&mut self) {
129        self.map.insert(CRATE_DEF_ID, EffectiveVisibility::from_vis(Visibility::Public));
130    }
131
132    // FIXME: Share code with `fn update`.
133    pub fn update_eff_vis(
134        &mut self,
135        def_id: LocalDefId,
136        eff_vis: &EffectiveVisibility,
137        tcx: TyCtxt<'_>,
138    ) {
139        match self.map.entry(def_id) {
140            IndexEntry::Occupied(mut occupied) => {
141                let old_eff_vis = occupied.get_mut();
142                for l in Level::all_levels() {
143                    let vis_at_level = eff_vis.at_level(l);
144                    let old_vis_at_level = old_eff_vis.at_level_mut(l);
145                    if vis_at_level.greater_than(*old_vis_at_level, tcx) {
146                        *old_vis_at_level = *vis_at_level
147                    }
148                }
149                old_eff_vis
150            }
151            IndexEntry::Vacant(vacant) => vacant.insert(*eff_vis),
152        };
153    }
154
155    pub fn check_invariants(&self, tcx: TyCtxt<'_>) {
156        if !truecfg!(debug_assertions) {
157            return;
158        }
159        for (&def_id, ev) in &self.map {
160            // More direct visibility levels can never go farther than less direct ones,
161            // and all effective visibilities are larger or equal than private visibility.
162            let private_vis = Visibility::Restricted(tcx.parent_module_from_def_id(def_id));
163            let span = tcx.def_span(def_id.to_def_id());
164            if private_vis.greater_than(ev.direct, tcx) {
165                crate::util::bug::span_bug_fmt(span,
    format_args!("private {0:?} > direct {1:?}", private_vis, ev.direct));span_bug!(span, "private {:?} > direct {:?}", private_vis, ev.direct);
166            }
167            if ev.direct.greater_than(ev.reexported, tcx) {
168                crate::util::bug::span_bug_fmt(span,
    format_args!("direct {0:?} > reexported {1:?}", ev.direct,
        ev.reexported));span_bug!(span, "direct {:?} > reexported {:?}", ev.direct, ev.reexported);
169            }
170            if ev.reexported.greater_than(ev.reachable, tcx) {
171                crate::util::bug::span_bug_fmt(span,
    format_args!("reexported {0:?} > reachable {1:?}", ev.reexported,
        ev.reachable));span_bug!(span, "reexported {:?} > reachable {:?}", ev.reexported, ev.reachable);
172            }
173            if ev.reachable.greater_than(ev.reachable_through_impl_trait, tcx) {
174                crate::util::bug::span_bug_fmt(span,
    format_args!("reachable {0:?} > reachable_through_impl_trait {1:?}",
        ev.reachable, ev.reachable_through_impl_trait));span_bug!(
175                    span,
176                    "reachable {:?} > reachable_through_impl_trait {:?}",
177                    ev.reachable,
178                    ev.reachable_through_impl_trait
179                );
180            }
181            // All effective visibilities except `reachable_through_impl_trait` are limited to
182            // nominal visibility. For some items nominal visibility doesn't make sense so we
183            // don't check this condition for them.
184            let is_impl = #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(def_id) {
    DefKind::Impl { .. } => true,
    _ => false,
}matches!(tcx.def_kind(def_id), DefKind::Impl { .. });
185            if !is_impl && tcx.trait_impl_of_assoc(def_id.to_def_id()).is_none() {
186                let nominal_vis = tcx.visibility(def_id);
187                if ev.reachable.greater_than(nominal_vis, tcx) {
188                    if let Node::Item(item) = tcx.hir_node_by_def_id(def_id)
189                        && let ItemKind::Use(_, UseKind::Glob) = item.kind
190                    {
191                        // Glob import visibilities can be increased by other
192                        // more public glob imports in cases of ambiguity.
193                    } else {
194                        crate::util::bug::span_bug_fmt(span,
    format_args!("{0:?}: reachable {1:?} > nominal {2:?}", def_id,
        ev.reachable, nominal_vis));span_bug!(
195                            span,
196                            "{:?}: reachable {:?} > nominal {:?}",
197                            def_id,
198                            ev.reachable,
199                            nominal_vis,
200                        );
201                    }
202                }
203            }
204        }
205    }
206}
207
208impl<Id: Eq + Hash> EffectiveVisibilities<Id> {
209    pub fn iter(&self) -> impl Iterator<Item = (&Id, &EffectiveVisibility)> {
210        self.map.iter()
211    }
212
213    pub fn effective_vis(&self, id: Id) -> Option<&EffectiveVisibility> {
214        self.map.get(&id)
215    }
216
217    pub fn effective_vis_or_private(
218        &mut self,
219        id: Id,
220        lazy_private_vis: impl FnOnce() -> Visibility,
221    ) -> &mut EffectiveVisibility {
222        self.map.entry(id).or_insert_with(|| EffectiveVisibility::from_vis(lazy_private_vis()))
223    }
224
225    pub fn update(
226        &mut self,
227        id: Id,
228        max_vis: Option<Visibility>,
229        lazy_private_vis: impl FnOnce() -> Visibility,
230        inherited_effective_vis: EffectiveVisibility,
231        level: Level,
232        tcx: TyCtxt<'_>,
233    ) -> bool {
234        let mut changed = false;
235        let current_effective_vis = self.effective_vis_or_private(id, lazy_private_vis);
236
237        let mut inherited_effective_vis_at_prev_level = *inherited_effective_vis.at_level(level);
238        let mut calculated_effective_vis = inherited_effective_vis_at_prev_level;
239        for l in Level::all_levels() {
240            if level >= l {
241                let inherited_effective_vis_at_level = *inherited_effective_vis.at_level(l);
242                let current_effective_vis_at_level = current_effective_vis.at_level_mut(l);
243                // effective visibility for id shouldn't be recalculated if
244                // inherited from parent_id effective visibility isn't changed at next level
245                if !(inherited_effective_vis_at_prev_level == inherited_effective_vis_at_level
246                    && level != l)
247                {
248                    // FIXME: figure out why unordered visibilities occur here,
249                    // and what the behavior for them should be.
250                    calculated_effective_vis = if let Some(max_vis) = max_vis
251                        && inherited_effective_vis_at_level.partial_cmp(max_vis, tcx)
252                            == Some(Ordering::Greater)
253                    {
254                        max_vis
255                    } else {
256                        inherited_effective_vis_at_level
257                    }
258                }
259                // effective visibility can't be decreased at next update call for the
260                // same id
261                // FIXME: figure out why unordered visibilities occur here,
262                // and what the behavior for them should be.
263                if calculated_effective_vis.partial_cmp(*current_effective_vis_at_level, tcx)
264                    == Some(Ordering::Greater)
265                {
266                    changed = true;
267                    *current_effective_vis_at_level = calculated_effective_vis;
268                }
269                inherited_effective_vis_at_prev_level = inherited_effective_vis_at_level;
270            }
271        }
272
273        changed
274    }
275}
276
277impl<Id> Default for EffectiveVisibilities<Id> {
278    fn default() -> Self {
279        EffectiveVisibilities { map: Default::default() }
280    }
281}
282
283impl StableHash for EffectiveVisibilities {
284    fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
285        let EffectiveVisibilities { ref map } = *self;
286        map.stable_hash(hcx, hasher);
287    }
288}