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]
#[doc(hidden)]
unsafe impl<'ra> ::core::clone::TrivialClone for ParentId<'ra> { }
#[automatically_derived]
impl<'ra> ::core::clone::Clone for ParentId<'ra> {
    #[inline]
    fn clone(&self) -> Self {
        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                let root = r.owners[&import.root_id].def_id;
114                // The `unreachable_pub` lint also needs to know whether any of the nested entries are
115                // exported by this use statement.
116                // FIXME: We could compute this lazily in `unreachable_pub` directly, but this is less invasive.
117                r.effective_visibilities.update_eff_vis(root, eff_vis, r.tcx);
118            }
119            if decl.ambiguity.get().is_some() && eff_vis.is_public_at_level(Level::Reexported) {
120                exported_ambiguities.insert(*decl);
121            }
122        }
123
124        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_resolve/src/effective_visibilities.rs:124",
                        "rustc_resolve::effective_visibilities",
                        ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_resolve/src/effective_visibilities.rs"),
                        ::tracing_core::__macro_support::Option::Some(124u32),
                        ::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);
125
126        exported_ambiguities
127    }
128
129    /// Update effective visibilities of name declarations in the given module,
130    /// including their whole reexport chains.
131    fn set_bindings_effective_visibilities(&mut self, module_id: LocalDefId) {
132        let module = self.r.expect_module(module_id.to_def_id());
133        for (_, name_resolution) in self.r.resolutions(module).iter() {
134            let Some(decl) = name_resolution.borrow(self.r).best_decl() else {
135                continue;
136            };
137            self.update_decl_chain(decl, ParentId::Def(module_id), &mut FxHashSet::default());
138        }
139    }
140
141    /// Update effective visibilities for the whole reexport chain of a declaration.
142    /// Set the given effective visibility level to `Level::Direct` and
143    /// sets the rest of the `use` chain to `Level::Reexported` until
144    /// we hit the actual exported item.
145    fn update_decl_chain(
146        &mut self,
147        mut decl: Decl<'ra>,
148        mut parent_id: ParentId<'ra>,
149        seen_most_visible: &mut FxHashSet<Decl<'ra>>,
150    ) {
151        let priv_vis = |this: &Self, parent_id, decl| match parent_id {
152            ParentId::Def(_) => this.current_private_vis,
153            ParentId::Import(_) => this.r.private_vis_decl(decl),
154        };
155        while let DeclKind::Import { source_decl, .. } = decl.kind {
156            self.update_import(decl, parent_id, priv_vis(self, parent_id, decl));
157            // `ambiguity_vis_max` can cycle on mutual globs; follow each once.
158            if let Some(most_visible) = decl.ambiguity_vis_max.get()
159                && seen_most_visible.insert(most_visible)
160            {
161                self.update_decl_chain(most_visible, parent_id, seen_most_visible);
162            }
163            parent_id = ParentId::Import(decl);
164            decl = source_decl;
165        }
166        if let Some(def_id) = decl.res().opt_def_id().and_then(|id| id.as_local()) {
167            let priv_vis = priv_vis(self, parent_id, decl);
168            self.update_def(def_id, decl.vis().expect_local(), parent_id, priv_vis);
169        }
170    }
171
172    fn effective_vis_or_private(&mut self, parent_id: ParentId<'ra>) -> EffectiveVisibility {
173        // Private nodes are only added to the table for caching, they could be added or removed at
174        // any moment without consequences, so we don't set `changed` to true when adding them.
175        *match parent_id {
176            ParentId::Def(def_id) => self
177                .def_effective_visibilities
178                .effective_vis_or_private(def_id, || self.r.private_vis_def(def_id)),
179            ParentId::Import(binding) => self
180                .import_effective_visibilities
181                .effective_vis_or_private(binding, || self.r.private_vis_decl(binding)),
182        }
183    }
184
185    /// All effective visibilities for a node are larger or equal than private visibility
186    /// for that node (see `check_invariants` in middle/privacy.rs).
187    /// So if either parent or nominal visibility is the same as private visibility, then
188    /// `min(parent_vis, nominal_vis) <= priv_vis`, and the update logic is guaranteed
189    /// to not update anything and we can skip it.
190    fn may_update(
191        &self,
192        nominal_vis: Visibility,
193        parent_id: ParentId<'_>,
194        priv_vis: Visibility,
195    ) -> bool {
196        nominal_vis != priv_vis
197            && match parent_id {
198                ParentId::Def(def_id) => self.r.tcx.local_visibility(def_id),
199                ParentId::Import(decl) => decl.vis().expect_local(),
200            } != priv_vis
201    }
202
203    fn update_import(&mut self, decl: Decl<'ra>, parent_id: ParentId<'ra>, priv_vis: Visibility) {
204        let nominal_vis = decl.vis().expect_local();
205        if !self.may_update(nominal_vis, parent_id, priv_vis) {
206            return;
207        };
208        let inherited_eff_vis = self.effective_vis_or_private(parent_id);
209        let tcx = self.r.tcx;
210        self.changed |= self.import_effective_visibilities.update(
211            decl,
212            Some(nominal_vis),
213            priv_vis,
214            inherited_eff_vis,
215            parent_id.level(),
216            tcx,
217        );
218    }
219
220    fn update_def(
221        &mut self,
222        def_id: LocalDefId,
223        nominal_vis: Visibility,
224        parent_id: ParentId<'ra>,
225        priv_vis: Visibility,
226    ) {
227        if !self.may_update(nominal_vis, parent_id, priv_vis) {
228            return;
229        };
230        let inherited_eff_vis = self.effective_vis_or_private(parent_id);
231        let tcx = self.r.tcx;
232        self.changed |= self.def_effective_visibilities.update(
233            def_id,
234            Some(nominal_vis),
235            priv_vis,
236            inherited_eff_vis,
237            parent_id.level(),
238            tcx,
239        );
240    }
241
242    fn update_field(&mut self, def_id: LocalDefId, parent_id: LocalDefId) {
243        let nominal_vis = self.r.tcx.local_visibility(def_id);
244        self.update_def(def_id, nominal_vis, ParentId::Def(parent_id), self.current_private_vis);
245    }
246
247    fn update_macro(&mut self, def_id: LocalDefId, inherited_effective_vis: EffectiveVisibility) {
248        let max_vis = Some(self.r.tcx.local_visibility(def_id));
249        let priv_vis = if def_id == CRATE_DEF_ID {
250            Visibility::Restricted(CRATE_MOD_ID)
251        } else {
252            self.r.private_vis_def(def_id)
253        };
254        self.changed |= self.def_effective_visibilities.update(
255            def_id,
256            max_vis,
257            priv_vis,
258            inherited_effective_vis,
259            Level::Reachable,
260            self.r.tcx,
261        );
262    }
263
264    // We have to make sure that the items that macros might reference
265    // are reachable, since they might be exported transitively.
266    fn update_reachability_from_macro(
267        &mut self,
268        local_def_id: LocalDefId,
269        md: &ast::MacroDef,
270        attrs: &[Attribute],
271    ) {
272        // Non-opaque macros cannot make other items more accessible than they already are.
273        if rustc_ast::attr::find_by_name(attrs, sym::rustc_macro_transparency)
274            .map_or(md.macro_rules, |attr| attr.value_str() != Some(sym::opaque))
275        {
276            return;
277        }
278
279        let macro_module_def_id = self.r.tcx.local_parent(local_def_id);
280        if self.r.tcx.def_kind(macro_module_def_id) != DefKind::Mod {
281            // The macro's parent doesn't correspond to a `mod`, return early (#63164, #65252).
282            return;
283        }
284
285        let Some(macro_ev) = self
286            .def_effective_visibilities
287            .effective_vis(local_def_id)
288            .filter(|ev| ev.public_at_level().is_some())
289            .copied()
290        else {
291            return;
292        };
293
294        // Since we are starting from an externally visible module,
295        // all the parents in the loop below are also guaranteed to be modules.
296        let mut module_def_id = macro_module_def_id;
297        loop {
298            self.update_macro_reachable(module_def_id, macro_module_def_id, macro_ev);
299            if module_def_id == CRATE_DEF_ID {
300                break;
301            }
302            module_def_id = self.r.tcx.local_parent(module_def_id);
303        }
304    }
305
306    /// Updates the item as being reachable through a macro defined in the given
307    /// module. Returns `true` if the level has changed.
308    fn update_macro_reachable(
309        &mut self,
310        module_def_id: LocalDefId,
311        defining_mod: LocalDefId,
312        macro_ev: EffectiveVisibility,
313    ) {
314        if self.macro_reachable.insert((module_def_id, defining_mod)) {
315            let module = self.r.expect_module(module_def_id.to_def_id());
316            for (_, name_resolution) in self.r.resolutions(module).iter() {
317                let Some(decl) = name_resolution.borrow(self.r).best_decl() else {
318                    continue;
319                };
320
321                if let Res::Def(def_kind, def_id) = decl.res()
322                    && let Some(def_id) = def_id.as_local()
323                    // FIXME: defs should be checked with `EffectiveVisibilities::is_reachable`.
324                    && decl.vis().is_accessible_from(defining_mod, self.r.tcx)
325                {
326                    let vis = self.r.tcx.local_visibility(def_id);
327                    self.update_macro_reachable_def(def_id, def_kind, vis, defining_mod, macro_ev);
328                }
329            }
330        }
331    }
332
333    fn update_macro_reachable_def(
334        &mut self,
335        def_id: LocalDefId,
336        def_kind: DefKind,
337        vis: Visibility,
338        module: LocalDefId,
339        macro_ev: EffectiveVisibility,
340    ) {
341        self.update_macro(def_id, macro_ev);
342
343        match def_kind {
344            DefKind::Mod => {
345                if vis.is_accessible_from(module, self.r.tcx) {
346                    self.update_macro_reachable(def_id, module, macro_ev);
347                }
348            }
349            DefKind::Struct | DefKind::Union => {
350                self.r.macro_reachable_adts.entry(def_id).or_default().insert(module);
351            }
352            _ => {}
353        }
354    }
355}
356
357impl<'a, 'ra, 'tcx> Visitor<'a> for EffectiveVisibilitiesVisitor<'a, 'ra, 'tcx> {
358    fn visit_item(&mut self, item: &'a ast::Item) {
359        let def_id = self.r.owner_def_id(item.id);
360        // Update effective visibilities of nested items.
361        // If it's a mod, also make the visitor walk all of its items
362        match &item.kind {
363            // Resolved in rustc_privacy when types are available
364            ast::ItemKind::Impl(..) => return,
365
366            // Should be unreachable at this stage
367            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!(
368                "ast::ItemKind::MacCall encountered, this should not anymore appear at this stage"
369            ),
370
371            ast::ItemKind::Mod(..) => {
372                let prev_private_vis = mem::replace(
373                    &mut self.current_private_vis,
374                    Visibility::Restricted(LocalModId::new_unchecked(def_id)),
375                );
376                self.set_bindings_effective_visibilities(def_id);
377                visit::walk_item(self, item);
378                self.current_private_vis = prev_private_vis;
379            }
380
381            ast::ItemKind::Enum(_, _, EnumDef { variants }) => {
382                self.set_bindings_effective_visibilities(def_id);
383                for variant in variants {
384                    let variant_def_id = self.r.child_def_id(item.id, variant.id);
385                    for field in variant.data.fields() {
386                        self.update_field(self.r.child_def_id(item.id, field.id), variant_def_id);
387                    }
388                }
389            }
390
391            ast::ItemKind::Struct(_, _, def) | ast::ItemKind::Union(_, _, def) => {
392                for field in def.fields() {
393                    self.update_field(self.r.child_def_id(item.id, field.id), def_id);
394                }
395            }
396
397            ast::ItemKind::Trait(..) => {
398                self.set_bindings_effective_visibilities(def_id);
399            }
400
401            ast::ItemKind::MacroDef(_, macro_def) => {
402                self.update_reachability_from_macro(def_id, macro_def, &item.attrs);
403            }
404
405            ast::ItemKind::ExternCrate(..)
406            | ast::ItemKind::Use(..)
407            | ast::ItemKind::Static(..)
408            | ast::ItemKind::Const(..)
409            | ast::ItemKind::ConstBlock(..)
410            | ast::ItemKind::GlobalAsm(..)
411            | ast::ItemKind::TyAlias(..)
412            | ast::ItemKind::TraitAlias(..)
413            | ast::ItemKind::ForeignMod(..)
414            | ast::ItemKind::Fn(..)
415            | ast::ItemKind::Delegation(..)
416            | ast::ItemKind::TestBinderConstraints(..) => return,
417        }
418    }
419}