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::{NameBinding, NameBindingKind, Resolver};
12
13#[derive(Clone, Copy)]
14enum ParentId<'ra> {
15    Def(LocalDefId),
16    Import(NameBinding<'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-binding, and def id
32    /// keys in `Resolver::effective_visibilities` are not enough for that, because multiple
33    /// bindings can correspond to a single def id in imports. So we keep a separate table.
34    import_effective_visibilities: EffectiveVisibilities<NameBinding<'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(&mut 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(&mut self, binding: NameBinding<'_>) -> Visibility {
46        let NameBindingKind::Import { import, .. } = binding.kind else { 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(&mut 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<NameBinding<'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 binding-based
95        // information, but are used by later passes. Effective visibility of an import def id
96        // is the maximum value among visibilities of bindings corresponding to that def id.
97        for (binding, eff_vis) in visitor.import_effective_visibilities.iter() {
98            let NameBindingKind::Import { import, .. } = binding.kind else { unreachable!() };
99            if !binding.is_ambiguity_recursive() {
100                if let Some(node_id) = import.id() {
101                    r.effective_visibilities.update_eff_vis(r.local_def_id(node_id), eff_vis, r.tcx)
102                }
103            } else if binding.ambiguity.is_some() && eff_vis.is_public_at_level(Level::Reexported) {
104                exported_ambiguities.insert(*binding);
105            }
106        }
107
108        info!("resolve::effective_visibilities: {:#?}", r.effective_visibilities);
109
110        exported_ambiguities
111    }
112
113    /// Update effective visibilities of bindings in the given module,
114    /// including their whole reexport chains.
115    fn set_bindings_effective_visibilities(&mut self, module_id: LocalDefId) {
116        assert!(self.r.module_map.contains_key(&module_id.to_def_id()));
117        let module = self.r.get_module(module_id.to_def_id()).unwrap();
118        let resolutions = self.r.resolutions(module);
119
120        for (_, name_resolution) in resolutions.borrow().iter() {
121            let Some(mut binding) = name_resolution.borrow().binding() else {
122                continue;
123            };
124            // Set the given effective visibility level to `Level::Direct` and
125            // sets the rest of the `use` chain to `Level::Reexported` until
126            // we hit the actual exported item.
127            //
128            // If the binding is ambiguous, put the root ambiguity binding and all reexports
129            // leading to it into the table. They are used by the `ambiguous_glob_reexports`
130            // lint. For all bindings added to the table this way `is_ambiguity` returns true.
131            let is_ambiguity =
132                |binding: NameBinding<'ra>, warn: bool| binding.ambiguity.is_some() && !warn;
133            let mut parent_id = ParentId::Def(module_id);
134            let mut warn_ambiguity = binding.warn_ambiguity;
135            while let NameBindingKind::Import { binding: nested_binding, .. } = binding.kind {
136                self.update_import(binding, parent_id);
137
138                if is_ambiguity(binding, warn_ambiguity) {
139                    // Stop at the root ambiguity, further bindings in the chain should not
140                    // be reexported because the root ambiguity blocks any access to them.
141                    // (Those further bindings are most likely not ambiguities themselves.)
142                    break;
143                }
144
145                parent_id = ParentId::Import(binding);
146                binding = nested_binding;
147                warn_ambiguity |= nested_binding.warn_ambiguity;
148            }
149            if !is_ambiguity(binding, warn_ambiguity)
150                && let Some(def_id) = binding.res().opt_def_id().and_then(|id| id.as_local())
151            {
152                self.update_def(def_id, binding.vis.expect_local(), parent_id);
153            }
154        }
155    }
156
157    fn effective_vis_or_private(&mut self, parent_id: ParentId<'ra>) -> EffectiveVisibility {
158        // Private nodes are only added to the table for caching, they could be added or removed at
159        // any moment without consequences, so we don't set `changed` to true when adding them.
160        *match parent_id {
161            ParentId::Def(def_id) => self
162                .def_effective_visibilities
163                .effective_vis_or_private(def_id, || self.r.private_vis_def(def_id)),
164            ParentId::Import(binding) => self
165                .import_effective_visibilities
166                .effective_vis_or_private(binding, || self.r.private_vis_import(binding)),
167        }
168    }
169
170    /// All effective visibilities for a node are larger or equal than private visibility
171    /// for that node (see `check_invariants` in middle/privacy.rs).
172    /// So if either parent or nominal visibility is the same as private visibility, then
173    /// `min(parent_vis, nominal_vis) <= private_vis`, and the update logic is guaranteed
174    /// to not update anything and we can skip it.
175    ///
176    /// We are checking this condition only if the correct value of private visibility is
177    /// cheaply available, otherwise it doesn't make sense performance-wise.
178    ///
179    /// `None` is returned if the update can be skipped,
180    /// and cheap private visibility is returned otherwise.
181    fn may_update(
182        &self,
183        nominal_vis: Visibility,
184        parent_id: ParentId<'_>,
185    ) -> Option<Option<Visibility>> {
186        match parent_id {
187            ParentId::Def(def_id) => (nominal_vis != self.current_private_vis
188                && self.r.tcx.local_visibility(def_id) != self.current_private_vis)
189                .then_some(Some(self.current_private_vis)),
190            ParentId::Import(_) => Some(None),
191        }
192    }
193
194    fn update_import(&mut self, binding: NameBinding<'ra>, parent_id: ParentId<'ra>) {
195        let nominal_vis = binding.vis.expect_local();
196        let Some(cheap_private_vis) = self.may_update(nominal_vis, parent_id) else { return };
197        let inherited_eff_vis = self.effective_vis_or_private(parent_id);
198        let tcx = self.r.tcx;
199        self.changed |= self.import_effective_visibilities.update(
200            binding,
201            Some(nominal_vis),
202            || cheap_private_vis.unwrap_or_else(|| self.r.private_vis_import(binding)),
203            inherited_eff_vis,
204            parent_id.level(),
205            tcx,
206        );
207    }
208
209    fn update_def(
210        &mut self,
211        def_id: LocalDefId,
212        nominal_vis: Visibility,
213        parent_id: ParentId<'ra>,
214    ) {
215        let Some(cheap_private_vis) = self.may_update(nominal_vis, parent_id) else { return };
216        let inherited_eff_vis = self.effective_vis_or_private(parent_id);
217        let tcx = self.r.tcx;
218        self.changed |= self.def_effective_visibilities.update(
219            def_id,
220            Some(nominal_vis),
221            || cheap_private_vis.unwrap_or_else(|| self.r.private_vis_def(def_id)),
222            inherited_eff_vis,
223            parent_id.level(),
224            tcx,
225        );
226    }
227
228    fn update_field(&mut self, def_id: LocalDefId, parent_id: LocalDefId) {
229        self.update_def(def_id, self.r.tcx.local_visibility(def_id), ParentId::Def(parent_id));
230    }
231}
232
233impl<'a, 'ra, 'tcx> Visitor<'a> for EffectiveVisibilitiesVisitor<'a, 'ra, 'tcx> {
234    fn visit_item(&mut self, item: &'a ast::Item) {
235        let def_id = self.r.local_def_id(item.id);
236        // Update effective visibilities of nested items.
237        // If it's a mod, also make the visitor walk all of its items
238        match item.kind {
239            // Resolved in rustc_privacy when types are available
240            ast::ItemKind::Impl(..) => return,
241
242            // Should be unreachable at this stage
243            ast::ItemKind::MacCall(..) | ast::ItemKind::DelegationMac(..) => panic!(
244                "ast::ItemKind::MacCall encountered, this should not anymore appear at this stage"
245            ),
246
247            ast::ItemKind::Mod(..) => {
248                let prev_private_vis =
249                    mem::replace(&mut self.current_private_vis, Visibility::Restricted(def_id));
250                self.set_bindings_effective_visibilities(def_id);
251                visit::walk_item(self, item);
252                self.current_private_vis = prev_private_vis;
253            }
254
255            ast::ItemKind::Enum(EnumDef { ref variants }, _) => {
256                self.set_bindings_effective_visibilities(def_id);
257                for variant in variants {
258                    let variant_def_id = self.r.local_def_id(variant.id);
259                    for field in variant.data.fields() {
260                        self.update_field(self.r.local_def_id(field.id), variant_def_id);
261                    }
262                }
263            }
264
265            ast::ItemKind::Struct(ref def, _) | ast::ItemKind::Union(ref def, _) => {
266                for field in def.fields() {
267                    self.update_field(self.r.local_def_id(field.id), def_id);
268                }
269            }
270
271            ast::ItemKind::Trait(..) => {
272                self.set_bindings_effective_visibilities(def_id);
273            }
274
275            ast::ItemKind::ExternCrate(..)
276            | ast::ItemKind::Use(..)
277            | ast::ItemKind::Static(..)
278            | ast::ItemKind::Const(..)
279            | ast::ItemKind::GlobalAsm(..)
280            | ast::ItemKind::TyAlias(..)
281            | ast::ItemKind::TraitAlias(..)
282            | ast::ItemKind::MacroDef(..)
283            | ast::ItemKind::ForeignMod(..)
284            | ast::ItemKind::Fn(..)
285            | ast::ItemKind::Delegation(..) => return,
286        }
287    }
288}