Skip to main content

rustc_resolve/
effective_visibilities.rs

1use std::mem;
2
3use rustc_ast::visit::Visitor;
4use rustc_ast::{Attribute, Crate, EnumDef, ast, visit};
5use rustc_data_structures::fx::FxHashSet;
6use rustc_hir::def::{DefKind, Res};
7use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId};
8use rustc_middle::middle::privacy::{EffectiveVisibilities, EffectiveVisibility, Level};
9use rustc_middle::ty::Visibility;
10use rustc_span::sym;
11use tracing::info;
12
13use crate::{Decl, DeclKind, Resolver};
14
15#[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)]
16enum ParentId<'ra> {
17    Def(LocalDefId),
18    Import(Decl<'ra>),
19}
20
21impl ParentId<'_> {
22    fn level(self) -> Level {
23        match self {
24            ParentId::Def(_) => Level::Direct,
25            ParentId::Import(_) => Level::Reexported,
26        }
27    }
28}
29
30pub(crate) struct EffectiveVisibilitiesVisitor<'a, 'ra, 'tcx> {
31    r: &'a mut Resolver<'ra, 'tcx>,
32    def_effective_visibilities: EffectiveVisibilities,
33    /// While walking import chains we need to track effective visibilities per-decl, and def id
34    /// keys in `Resolver::effective_visibilities` are not enough for that, because multiple
35    /// declarations can correspond to a single def id in imports. So we keep a separate table.
36    import_effective_visibilities: EffectiveVisibilities<Decl<'ra>>,
37    // It's possible to recalculate this at any point, but it's relatively expensive.
38    current_private_vis: Visibility,
39    /// A set of pairs corresponding to modules, where the first module is
40    /// reachable via a macro that's defined in the second module. This cannot
41    /// be represented as reachable because it can't handle the following case:
42    ///
43    /// pub mod n {                         // Should be `Public`
44    ///     pub(crate) mod p {              // Should *not* be accessible
45    ///         pub fn f() -> i32 { 12 }    // Must be `Reachable`
46    ///     }
47    /// }
48    /// pub macro m() {
49    ///     n::p::f()
50    /// }
51    macro_reachable: FxHashSet<(LocalDefId, LocalDefId)>,
52    changed: bool,
53}
54
55impl Resolver<'_, '_> {
56    fn private_vis_decl(&self, decl: Decl<'_>) -> Visibility {
57        Visibility::Restricted(
58            decl.parent_module.map_or(CRATE_DEF_ID, |m| m.nearest_parent_mod().expect_local()),
59        )
60    }
61
62    fn private_vis_def(&self, def_id: LocalDefId) -> Visibility {
63        // For mod items `normal_mod_id` will be equal to `def_id`, but we actually need its parent.
64        let normal_mod_id = self
65            .get_nearest_non_block_module(def_id.to_def_id())
66            .nearest_parent_mod()
67            .expect_local();
68        if normal_mod_id == def_id {
69            Visibility::Restricted(self.tcx.local_parent(def_id))
70        } else {
71            Visibility::Restricted(normal_mod_id)
72        }
73    }
74}
75
76impl<'a, 'ra, 'tcx> EffectiveVisibilitiesVisitor<'a, 'ra, 'tcx> {
77    /// Fills the `Resolver::effective_visibilities` table with public & exported items
78    /// For now, this doesn't resolve macros (FIXME) and cannot resolve Impl, as we
79    /// need access to a TyCtxt for that. Returns the set of ambiguous re-exports.
80    pub(crate) fn compute_effective_visibilities<'c>(
81        r: &'a mut Resolver<'ra, 'tcx>,
82        krate: &'c Crate,
83    ) -> FxHashSet<Decl<'ra>> {
84        let mut visitor = EffectiveVisibilitiesVisitor {
85            r,
86            def_effective_visibilities: Default::default(),
87            import_effective_visibilities: Default::default(),
88            current_private_vis: Visibility::Restricted(CRATE_DEF_ID),
89            macro_reachable: Default::default(),
90            changed: true,
91        };
92
93        visitor.def_effective_visibilities.update_root();
94        visitor.set_bindings_effective_visibilities(CRATE_DEF_ID);
95
96        while visitor.changed {
97            visitor.changed = false;
98            visit::walk_crate(&mut visitor, krate);
99        }
100        visitor.r.effective_visibilities = visitor.def_effective_visibilities;
101
102        let mut exported_ambiguities = FxHashSet::default();
103
104        // Update visibilities for import def ids. These are not used during the
105        // `EffectiveVisibilitiesVisitor` pass, because we have more detailed declaration-based
106        // information, but are used by later passes. Effective visibility of an import def id
107        // is the maximum value among visibilities of declarations corresponding to that def id.
108        for (decl, eff_vis) in visitor.import_effective_visibilities.iter() {
109            let DeclKind::Import { import, .. } = decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
110            if let Some(def_id) = import.def_id() {
111                r.effective_visibilities.update_eff_vis(def_id, eff_vis, r.tcx)
112            }
113            if decl.ambiguity.get().is_some() && eff_vis.is_public_at_level(Level::Reexported) {
114                exported_ambiguities.insert(*decl);
115            }
116        }
117
118        {
    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:118",
                        "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(118u32),
                        ::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);
119
120        exported_ambiguities
121    }
122
123    /// Update effective visibilities of name declarations in the given module,
124    /// including their whole reexport chains.
125    fn set_bindings_effective_visibilities(&mut self, module_id: LocalDefId) {
126        let module = self.r.expect_module(module_id.to_def_id());
127        for (_, name_resolution) in self.r.resolutions(module).borrow().iter() {
128            let Some(decl) = name_resolution.borrow().best_decl() else {
129                continue;
130            };
131            self.update_decl_chain(decl, ParentId::Def(module_id));
132        }
133    }
134
135    /// Update effective visibilities for the whole reexport chain of a declaration.
136    /// Set the given effective visibility level to `Level::Direct` and
137    /// sets the rest of the `use` chain to `Level::Reexported` until
138    /// we hit the actual exported item.
139    fn update_decl_chain(&mut self, mut decl: Decl<'ra>, mut parent_id: ParentId<'ra>) {
140        let priv_vis = |this: &Self, parent_id, decl| match parent_id {
141            ParentId::Def(_) => this.current_private_vis,
142            ParentId::Import(_) => this.r.private_vis_decl(decl),
143        };
144        while let DeclKind::Import { source_decl, .. } = decl.kind {
145            self.update_import(decl, parent_id, priv_vis(self, parent_id, decl));
146            if let Some(max_vis_decl) = decl.ambiguity_vis_max.get() {
147                // The name is exported with the visibility of the most visible declaration
148                // in its ambiguous glob set (see `DeclData::vis`), so everything on that
149                // declaration's reexport chain, including the final item, must get its
150                // effective visibility from that declaration as well. Otherwise the item
151                // would be considered unreachable by dead code analysis and metadata
152                // encoding despite being exported (see the regression test
153                // `ambiguous-import-visibility-globglob-mir.rs`).
154                // This also avoids the most visible import in an ambiguous glob set
155                // being reported as unused.
156                self.update_decl_chain(max_vis_decl, parent_id);
157            }
158            parent_id = ParentId::Import(decl);
159            decl = source_decl;
160        }
161        if let Some(def_id) = decl.res().opt_def_id().and_then(|id| id.as_local()) {
162            let priv_vis = priv_vis(self, parent_id, decl);
163            self.update_def(def_id, decl.vis().expect_local(), parent_id, priv_vis);
164        }
165    }
166
167    fn effective_vis_or_private(&mut self, parent_id: ParentId<'ra>) -> EffectiveVisibility {
168        // Private nodes are only added to the table for caching, they could be added or removed at
169        // any moment without consequences, so we don't set `changed` to true when adding them.
170        *match parent_id {
171            ParentId::Def(def_id) => self
172                .def_effective_visibilities
173                .effective_vis_or_private(def_id, || self.r.private_vis_def(def_id)),
174            ParentId::Import(binding) => self
175                .import_effective_visibilities
176                .effective_vis_or_private(binding, || self.r.private_vis_decl(binding)),
177        }
178    }
179
180    /// All effective visibilities for a node are larger or equal than private visibility
181    /// for that node (see `check_invariants` in middle/privacy.rs).
182    /// So if either parent or nominal visibility is the same as private visibility, then
183    /// `min(parent_vis, nominal_vis) <= priv_vis`, and the update logic is guaranteed
184    /// to not update anything and we can skip it.
185    fn may_update(
186        &self,
187        nominal_vis: Visibility,
188        parent_id: ParentId<'_>,
189        priv_vis: Visibility,
190    ) -> bool {
191        nominal_vis != priv_vis
192            && match parent_id {
193                ParentId::Def(def_id) => self.r.tcx.local_visibility(def_id),
194                ParentId::Import(decl) => decl.vis().expect_local(),
195            } != priv_vis
196    }
197
198    fn update_import(&mut self, decl: Decl<'ra>, parent_id: ParentId<'ra>, priv_vis: Visibility) {
199        let nominal_vis = decl.vis().expect_local();
200        if !self.may_update(nominal_vis, parent_id, priv_vis) {
201            return;
202        };
203        let inherited_eff_vis = self.effective_vis_or_private(parent_id);
204        let tcx = self.r.tcx;
205        self.changed |= self.import_effective_visibilities.update(
206            decl,
207            Some(nominal_vis),
208            priv_vis,
209            inherited_eff_vis,
210            parent_id.level(),
211            tcx,
212        );
213    }
214
215    fn update_def(
216        &mut self,
217        def_id: LocalDefId,
218        nominal_vis: Visibility,
219        parent_id: ParentId<'ra>,
220        priv_vis: Visibility,
221    ) {
222        if !self.may_update(nominal_vis, parent_id, priv_vis) {
223            return;
224        };
225        let inherited_eff_vis = self.effective_vis_or_private(parent_id);
226        let tcx = self.r.tcx;
227        self.changed |= self.def_effective_visibilities.update(
228            def_id,
229            Some(nominal_vis),
230            priv_vis,
231            inherited_eff_vis,
232            parent_id.level(),
233            tcx,
234        );
235    }
236
237    fn update_field(&mut self, def_id: LocalDefId, parent_id: LocalDefId) {
238        let nominal_vis = self.r.tcx.local_visibility(def_id);
239        self.update_def(def_id, nominal_vis, ParentId::Def(parent_id), self.current_private_vis);
240    }
241
242    fn update_macro(&mut self, def_id: LocalDefId, inherited_effective_vis: EffectiveVisibility) {
243        let max_vis = Some(self.r.tcx.local_visibility(def_id));
244        let priv_vis = if def_id == CRATE_DEF_ID {
245            Visibility::Restricted(CRATE_DEF_ID)
246        } else {
247            self.r.private_vis_def(def_id)
248        };
249        self.changed |= self.def_effective_visibilities.update(
250            def_id,
251            max_vis,
252            priv_vis,
253            inherited_effective_vis,
254            Level::Reachable,
255            self.r.tcx,
256        );
257    }
258
259    // We have to make sure that the items that macros might reference
260    // are reachable, since they might be exported transitively.
261    fn update_reachability_from_macro(
262        &mut self,
263        local_def_id: LocalDefId,
264        md: &ast::MacroDef,
265        attrs: &[Attribute],
266    ) {
267        // Non-opaque macros cannot make other items more accessible than they already are.
268        if rustc_ast::attr::find_by_name(attrs, sym::rustc_macro_transparency)
269            .map_or(md.macro_rules, |attr| attr.value_str() != Some(sym::opaque))
270        {
271            return;
272        }
273
274        let macro_module_def_id = self.r.tcx.local_parent(local_def_id);
275        if self.r.tcx.def_kind(macro_module_def_id) != DefKind::Mod {
276            // The macro's parent doesn't correspond to a `mod`, return early (#63164, #65252).
277            return;
278        }
279
280        let Some(macro_ev) = self
281            .def_effective_visibilities
282            .effective_vis(local_def_id)
283            .filter(|ev| ev.public_at_level().is_some())
284            .copied()
285        else {
286            return;
287        };
288
289        // Since we are starting from an externally visible module,
290        // all the parents in the loop below are also guaranteed to be modules.
291        let mut module_def_id = macro_module_def_id;
292        loop {
293            self.update_macro_reachable(module_def_id, macro_module_def_id, macro_ev);
294            if module_def_id == CRATE_DEF_ID {
295                break;
296            }
297            module_def_id = self.r.tcx.local_parent(module_def_id);
298        }
299    }
300
301    /// Updates the item as being reachable through a macro defined in the given
302    /// module. Returns `true` if the level has changed.
303    fn update_macro_reachable(
304        &mut self,
305        module_def_id: LocalDefId,
306        defining_mod: LocalDefId,
307        macro_ev: EffectiveVisibility,
308    ) {
309        if self.macro_reachable.insert((module_def_id, defining_mod)) {
310            let module = self.r.expect_module(module_def_id.to_def_id());
311            for (_, name_resolution) in self.r.resolutions(module).borrow().iter() {
312                let Some(decl) = name_resolution.borrow().best_decl() else {
313                    continue;
314                };
315
316                if let Res::Def(def_kind, def_id) = decl.res()
317                    && let Some(def_id) = def_id.as_local()
318                    // FIXME: defs should be checked with `EffectiveVisibilities::is_reachable`.
319                    && decl.vis().is_accessible_from(defining_mod, self.r.tcx)
320                {
321                    let vis = self.r.tcx.local_visibility(def_id);
322                    self.update_macro_reachable_def(def_id, def_kind, vis, defining_mod, macro_ev);
323                }
324            }
325        }
326    }
327
328    fn update_macro_reachable_def(
329        &mut self,
330        def_id: LocalDefId,
331        def_kind: DefKind,
332        vis: Visibility,
333        module: LocalDefId,
334        macro_ev: EffectiveVisibility,
335    ) {
336        self.update_macro(def_id, macro_ev);
337
338        match def_kind {
339            DefKind::Mod => {
340                if vis.is_accessible_from(module, self.r.tcx) {
341                    self.update_macro_reachable(def_id, module, macro_ev);
342                }
343            }
344            DefKind::Struct | DefKind::Union => {
345                self.r.macro_reachable_adts.entry(def_id).or_default().insert(module);
346            }
347            _ => {}
348        }
349    }
350}
351
352impl<'a, 'ra, 'tcx> Visitor<'a> for EffectiveVisibilitiesVisitor<'a, 'ra, 'tcx> {
353    fn visit_item(&mut self, item: &'a ast::Item) {
354        let def_id = self.r.owner_def_id(item.id);
355        // Update effective visibilities of nested items.
356        // If it's a mod, also make the visitor walk all of its items
357        match &item.kind {
358            // Resolved in rustc_privacy when types are available
359            ast::ItemKind::Impl(..) => return,
360
361            // Should be unreachable at this stage
362            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!(
363                "ast::ItemKind::MacCall encountered, this should not anymore appear at this stage"
364            ),
365
366            ast::ItemKind::Mod(..) => {
367                let prev_private_vis =
368                    mem::replace(&mut self.current_private_vis, Visibility::Restricted(def_id));
369                self.set_bindings_effective_visibilities(def_id);
370                visit::walk_item(self, item);
371                self.current_private_vis = prev_private_vis;
372            }
373
374            ast::ItemKind::Enum(_, _, EnumDef { variants }) => {
375                self.set_bindings_effective_visibilities(def_id);
376                for variant in variants {
377                    let variant_def_id = self.r.child_def_id(item.id, variant.id);
378                    for field in variant.data.fields() {
379                        self.update_field(self.r.child_def_id(item.id, field.id), variant_def_id);
380                    }
381                }
382            }
383
384            ast::ItemKind::Struct(_, _, def) | ast::ItemKind::Union(_, _, def) => {
385                for field in def.fields() {
386                    self.update_field(self.r.child_def_id(item.id, field.id), def_id);
387                }
388            }
389
390            ast::ItemKind::Trait(..) => {
391                self.set_bindings_effective_visibilities(def_id);
392            }
393
394            ast::ItemKind::MacroDef(_, macro_def) => {
395                self.update_reachability_from_macro(def_id, macro_def, &item.attrs);
396            }
397
398            ast::ItemKind::ExternCrate(..)
399            | ast::ItemKind::Use(..)
400            | ast::ItemKind::Static(..)
401            | ast::ItemKind::Const(..)
402            | ast::ItemKind::ConstBlock(..)
403            | ast::ItemKind::GlobalAsm(..)
404            | ast::ItemKind::TyAlias(..)
405            | ast::ItemKind::TraitAlias(..)
406            | ast::ItemKind::ForeignMod(..)
407            | ast::ItemKind::Fn(..)
408            | ast::ItemKind::Delegation(..) => return,
409        }
410    }
411}