Skip to main content

rustc_resolve/
effective_visibilities.rs

1use std::mem;
2
3use rustc_ast::visit::Visitor;
4use rustc_ast::{Crate, EnumDef, ast, visit};
5use rustc_data_structures::fx::FxHashSet;
6use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId};
7use rustc_middle::middle::privacy::{EffectiveVisibilities, EffectiveVisibility, Level};
8use rustc_middle::ty::Visibility;
9use tracing::info;
10
11use crate::{Decl, DeclKind, Resolver};
12
13#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for ParentId<'ra> {
    #[inline]
    fn clone(&self) -> ParentId<'ra> {
        let _: ::core::clone::AssertParamIsClone<LocalDefId>;
        let _: ::core::clone::AssertParamIsClone<Decl<'ra>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for ParentId<'ra> { }Copy)]
14enum ParentId<'ra> {
15    Def(LocalDefId),
16    Import(Decl<'ra>),
17}
18
19impl ParentId<'_> {
20    fn level(self) -> Level {
21        match self {
22            ParentId::Def(_) => Level::Direct,
23            ParentId::Import(_) => Level::Reexported,
24        }
25    }
26}
27
28pub(crate) struct EffectiveVisibilitiesVisitor<'a, 'ra, 'tcx> {
29    r: &'a mut Resolver<'ra, 'tcx>,
30    def_effective_visibilities: EffectiveVisibilities,
31    /// While walking import chains we need to track effective visibilities per-decl, and def id
32    /// keys in `Resolver::effective_visibilities` are not enough for that, because multiple
33    /// declarations can correspond to a single def id in imports. So we keep a separate table.
34    import_effective_visibilities: EffectiveVisibilities<Decl<'ra>>,
35    // It's possible to recalculate this at any point, but it's relatively expensive.
36    current_private_vis: Visibility,
37    changed: bool,
38}
39
40impl Resolver<'_, '_> {
41    fn nearest_normal_mod(&self, def_id: LocalDefId) -> LocalDefId {
42        self.get_nearest_non_block_module(def_id.to_def_id()).nearest_parent_mod().expect_local()
43    }
44
45    fn private_vis_import(&self, decl: Decl<'_>) -> Visibility {
46        let DeclKind::Import { import, .. } = decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
47        Visibility::Restricted(
48            import
49                .id()
50                .map(|id| self.nearest_normal_mod(self.local_def_id(id)))
51                .unwrap_or(CRATE_DEF_ID),
52        )
53    }
54
55    fn private_vis_def(&self, def_id: LocalDefId) -> Visibility {
56        // For mod items `nearest_normal_mod` returns its argument, but we actually need its parent.
57        let normal_mod_id = self.nearest_normal_mod(def_id);
58        if normal_mod_id == def_id {
59            Visibility::Restricted(self.tcx.local_parent(def_id))
60        } else {
61            Visibility::Restricted(normal_mod_id)
62        }
63    }
64}
65
66impl<'a, 'ra, 'tcx> EffectiveVisibilitiesVisitor<'a, 'ra, 'tcx> {
67    /// Fills the `Resolver::effective_visibilities` table with public & exported items
68    /// For now, this doesn't resolve macros (FIXME) and cannot resolve Impl, as we
69    /// need access to a TyCtxt for that. Returns the set of ambiguous re-exports.
70    pub(crate) fn compute_effective_visibilities<'c>(
71        r: &'a mut Resolver<'ra, 'tcx>,
72        krate: &'c Crate,
73    ) -> FxHashSet<Decl<'ra>> {
74        let mut visitor = EffectiveVisibilitiesVisitor {
75            r,
76            def_effective_visibilities: Default::default(),
77            import_effective_visibilities: Default::default(),
78            current_private_vis: Visibility::Restricted(CRATE_DEF_ID),
79            changed: true,
80        };
81
82        visitor.def_effective_visibilities.update_root();
83        visitor.set_bindings_effective_visibilities(CRATE_DEF_ID);
84
85        while visitor.changed {
86            visitor.changed = false;
87            visit::walk_crate(&mut visitor, krate);
88        }
89        visitor.r.effective_visibilities = visitor.def_effective_visibilities;
90
91        let mut exported_ambiguities = FxHashSet::default();
92
93        // Update visibilities for import def ids. These are not used during the
94        // `EffectiveVisibilitiesVisitor` pass, because we have more detailed declaration-based
95        // information, but are used by later passes. Effective visibility of an import def id
96        // is the maximum value among visibilities of declarations corresponding to that def id.
97        for (decl, eff_vis) in visitor.import_effective_visibilities.iter() {
98            let DeclKind::Import { import, .. } = decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
99            if let Some(node_id) = import.id() {
100                r.effective_visibilities.update_eff_vis(r.local_def_id(node_id), eff_vis, r.tcx)
101            }
102            if decl.ambiguity.get().is_some() && eff_vis.is_public_at_level(Level::Reexported) {
103                exported_ambiguities.insert(*decl);
104            }
105        }
106
107        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/effective_visibilities.rs:107",
                        "rustc_resolve::effective_visibilities",
                        ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/effective_visibilities.rs"),
                        ::tracing_core::__macro_support::Option::Some(107u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::effective_visibilities"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("resolve::effective_visibilities: {0:#?}",
                                                    r.effective_visibilities) as &dyn Value))])
            });
    } else { ; }
};info!("resolve::effective_visibilities: {:#?}", r.effective_visibilities);
108
109        exported_ambiguities
110    }
111
112    /// Update effective visibilities of name declarations in the given module,
113    /// including their whole reexport chains.
114    fn set_bindings_effective_visibilities(&mut self, module_id: LocalDefId) {
115        let module = self.r.expect_module(module_id.to_def_id());
116        for (_, name_resolution) in self.r.resolutions(module).borrow().iter() {
117            let Some(mut decl) = name_resolution.borrow().best_decl() else {
118                continue;
119            };
120            // Set the given effective visibility level to `Level::Direct` and
121            // sets the rest of the `use` chain to `Level::Reexported` until
122            // we hit the actual exported item.
123            let mut parent_id = ParentId::Def(module_id);
124            while let DeclKind::Import { source_decl, .. } = decl.kind {
125                self.update_import(decl, parent_id);
126                parent_id = ParentId::Import(decl);
127                decl = source_decl;
128            }
129            if let Some(def_id) = decl.res().opt_def_id().and_then(|id| id.as_local()) {
130                self.update_def(def_id, decl.vis().expect_local(), parent_id);
131            }
132        }
133    }
134
135    fn effective_vis_or_private(&mut self, parent_id: ParentId<'ra>) -> EffectiveVisibility {
136        // Private nodes are only added to the table for caching, they could be added or removed at
137        // any moment without consequences, so we don't set `changed` to true when adding them.
138        *match parent_id {
139            ParentId::Def(def_id) => self
140                .def_effective_visibilities
141                .effective_vis_or_private(def_id, || self.r.private_vis_def(def_id)),
142            ParentId::Import(binding) => self
143                .import_effective_visibilities
144                .effective_vis_or_private(binding, || self.r.private_vis_import(binding)),
145        }
146    }
147
148    /// All effective visibilities for a node are larger or equal than private visibility
149    /// for that node (see `check_invariants` in middle/privacy.rs).
150    /// So if either parent or nominal visibility is the same as private visibility, then
151    /// `min(parent_vis, nominal_vis) <= private_vis`, and the update logic is guaranteed
152    /// to not update anything and we can skip it.
153    ///
154    /// We are checking this condition only if the correct value of private visibility is
155    /// cheaply available, otherwise it doesn't make sense performance-wise.
156    ///
157    /// `None` is returned if the update can be skipped,
158    /// and cheap private visibility is returned otherwise.
159    fn may_update(
160        &self,
161        nominal_vis: Visibility,
162        parent_id: ParentId<'_>,
163    ) -> Option<Option<Visibility>> {
164        match parent_id {
165            ParentId::Def(def_id) => (nominal_vis != self.current_private_vis
166                && self.r.tcx.local_visibility(def_id) != self.current_private_vis)
167                .then_some(Some(self.current_private_vis)),
168            ParentId::Import(_) => Some(None),
169        }
170    }
171
172    fn update_import(&mut self, decl: Decl<'ra>, parent_id: ParentId<'ra>) {
173        let nominal_vis = decl.vis().expect_local();
174        let Some(cheap_private_vis) = self.may_update(nominal_vis, parent_id) else { return };
175        let inherited_eff_vis = self.effective_vis_or_private(parent_id);
176        let tcx = self.r.tcx;
177        self.changed |= self.import_effective_visibilities.update(
178            decl,
179            Some(nominal_vis),
180            || cheap_private_vis.unwrap_or_else(|| self.r.private_vis_import(decl)),
181            inherited_eff_vis,
182            parent_id.level(),
183            tcx,
184        );
185        if let Some(max_vis_decl) = decl.ambiguity_vis_max.get() {
186            // Avoid the most visible import in an ambiguous glob set being reported as unused.
187            self.update_import(max_vis_decl, parent_id);
188        }
189    }
190
191    fn update_def(
192        &mut self,
193        def_id: LocalDefId,
194        nominal_vis: Visibility,
195        parent_id: ParentId<'ra>,
196    ) {
197        let Some(cheap_private_vis) = self.may_update(nominal_vis, parent_id) else { return };
198        let inherited_eff_vis = self.effective_vis_or_private(parent_id);
199        let tcx = self.r.tcx;
200        self.changed |= self.def_effective_visibilities.update(
201            def_id,
202            Some(nominal_vis),
203            || cheap_private_vis.unwrap_or_else(|| self.r.private_vis_def(def_id)),
204            inherited_eff_vis,
205            parent_id.level(),
206            tcx,
207        );
208    }
209
210    fn update_field(&mut self, def_id: LocalDefId, parent_id: LocalDefId) {
211        self.update_def(def_id, self.r.tcx.local_visibility(def_id), ParentId::Def(parent_id));
212    }
213}
214
215impl<'a, 'ra, 'tcx> Visitor<'a> for EffectiveVisibilitiesVisitor<'a, 'ra, 'tcx> {
216    fn visit_item(&mut self, item: &'a ast::Item) {
217        let def_id = self.r.local_def_id(item.id);
218        // Update effective visibilities of nested items.
219        // If it's a mod, also make the visitor walk all of its items
220        match item.kind {
221            // Resolved in rustc_privacy when types are available
222            ast::ItemKind::Impl(..) => return,
223
224            // Should be unreachable at this stage
225            ast::ItemKind::MacCall(..) | ast::ItemKind::DelegationMac(..) => {
    ::core::panicking::panic_fmt(format_args!("ast::ItemKind::MacCall encountered, this should not anymore appear at this stage"));
}panic!(
226                "ast::ItemKind::MacCall encountered, this should not anymore appear at this stage"
227            ),
228
229            ast::ItemKind::Mod(..) => {
230                let prev_private_vis =
231                    mem::replace(&mut self.current_private_vis, Visibility::Restricted(def_id));
232                self.set_bindings_effective_visibilities(def_id);
233                visit::walk_item(self, item);
234                self.current_private_vis = prev_private_vis;
235            }
236
237            ast::ItemKind::Enum(_, _, EnumDef { ref variants }) => {
238                self.set_bindings_effective_visibilities(def_id);
239                for variant in variants {
240                    let variant_def_id = self.r.local_def_id(variant.id);
241                    for field in variant.data.fields() {
242                        self.update_field(self.r.local_def_id(field.id), variant_def_id);
243                    }
244                }
245            }
246
247            ast::ItemKind::Struct(_, _, ref def) | ast::ItemKind::Union(_, _, ref def) => {
248                for field in def.fields() {
249                    self.update_field(self.r.local_def_id(field.id), def_id);
250                }
251            }
252
253            ast::ItemKind::Trait(..) => {
254                self.set_bindings_effective_visibilities(def_id);
255            }
256
257            ast::ItemKind::ExternCrate(..)
258            | ast::ItemKind::Use(..)
259            | ast::ItemKind::Static(..)
260            | ast::ItemKind::Const(..)
261            | ast::ItemKind::ConstBlock(..)
262            | ast::ItemKind::GlobalAsm(..)
263            | ast::ItemKind::TyAlias(..)
264            | ast::ItemKind::TraitAlias(..)
265            | ast::ItemKind::MacroDef(..)
266            | ast::ItemKind::ForeignMod(..)
267            | ast::ItemKind::Fn(..)
268            | ast::ItemKind::Delegation(..) => return,
269        }
270    }
271}