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