]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/access_levels.rs
Auto merge of #99600 - tmiasko:subst-folder, r=petrochenkov
[rust.git] / compiler / rustc_resolve / src / access_levels.rs
1 use rustc_ast::ast;
2 use rustc_ast::visit;
3 use rustc_ast::visit::Visitor;
4 use rustc_ast::Crate;
5 use rustc_ast::EnumDef;
6 use rustc_ast::ForeignMod;
7 use rustc_ast::NodeId;
8 use rustc_hir::def_id::LocalDefId;
9 use rustc_hir::def_id::CRATE_DEF_ID;
10 use rustc_middle::middle::privacy::AccessLevel;
11 use rustc_middle::ty::Visibility;
12 use rustc_span::sym;
13
14 use crate::imports::ImportKind;
15 use crate::BindingKey;
16 use crate::NameBinding;
17 use crate::NameBindingKind;
18 use crate::Resolver;
19
20 pub struct AccessLevelsVisitor<'r, 'a> {
21     r: &'r mut Resolver<'a>,
22     prev_level: Option<AccessLevel>,
23     changed: bool,
24 }
25
26 impl<'r, 'a> AccessLevelsVisitor<'r, 'a> {
27     /// Fills the `Resolver::access_levels` table with public & exported items
28     /// For now, this doesn't resolve macros (FIXME) and cannot resolve Impl, as we
29     /// need access to a TyCtxt for that.
30     pub fn compute_access_levels<'c>(r: &'r mut Resolver<'a>, krate: &'c Crate) {
31         let mut visitor =
32             AccessLevelsVisitor { r, changed: false, prev_level: Some(AccessLevel::Public) };
33
34         visitor.set_access_level_def_id(CRATE_DEF_ID, Some(AccessLevel::Public));
35         visitor.set_exports_access_level(CRATE_DEF_ID);
36
37         while visitor.changed {
38             visitor.reset();
39             visit::walk_crate(&mut visitor, krate);
40         }
41
42         tracing::info!("resolve::access_levels: {:#?}", r.access_levels);
43     }
44
45     fn reset(&mut self) {
46         self.changed = false;
47         self.prev_level = Some(AccessLevel::Public);
48     }
49
50     /// Update the access level of the exports of the given module accordingly. The module access
51     /// level has to be Exported or Public.
52     /// This will also follow `use` chains (see PrivacyVisitor::set_import_binding_access_level).
53     fn set_exports_access_level(&mut self, module_id: LocalDefId) {
54         assert!(self.r.module_map.contains_key(&&module_id.to_def_id()));
55
56         // Set the given binding access level to `AccessLevel::Public` and
57         // sets the rest of the `use` chain to `AccessLevel::Exported` until
58         // we hit the actual exported item.
59         let set_import_binding_access_level =
60             |this: &mut Self, mut binding: &NameBinding<'a>, mut access_level| {
61                 while let NameBindingKind::Import { binding: nested_binding, import, .. } =
62                     binding.kind
63                 {
64                     this.set_access_level(import.id, access_level);
65                     if let ImportKind::Single { additional_ids, .. } = import.kind {
66                         this.set_access_level(additional_ids.0, access_level);
67                         this.set_access_level(additional_ids.1, access_level);
68                     }
69
70                     access_level = Some(AccessLevel::Exported);
71                     binding = nested_binding;
72                 }
73             };
74
75         let module_level = self.r.access_levels.map.get(&module_id).copied();
76         assert!(module_level >= Some(AccessLevel::Exported));
77
78         if let Some(exports) = self.r.reexport_map.get(&module_id) {
79             let pub_exports = exports
80                 .iter()
81                 .filter(|ex| ex.vis == Visibility::Public)
82                 .cloned()
83                 .collect::<Vec<_>>();
84
85             let module = self.r.get_module(module_id.to_def_id()).unwrap();
86             for export in pub_exports.into_iter() {
87                 if let Some(export_def_id) = export.res.opt_def_id().and_then(|id| id.as_local()) {
88                     self.set_access_level_def_id(export_def_id, Some(AccessLevel::Exported));
89                 }
90
91                 if let Some(ns) = export.res.ns() {
92                     let key = BindingKey { ident: export.ident, ns, disambiguator: 0 };
93                     let name_res = self.r.resolution(module, key);
94                     if let Some(binding) = name_res.borrow().binding() {
95                         set_import_binding_access_level(self, binding, module_level)
96                     }
97                 }
98             }
99         }
100     }
101
102     /// Sets the access level of the `LocalDefId` corresponding to the given `NodeId`.
103     /// This function will panic if the `NodeId` does not have a `LocalDefId`
104     fn set_access_level(
105         &mut self,
106         node_id: NodeId,
107         access_level: Option<AccessLevel>,
108     ) -> Option<AccessLevel> {
109         self.set_access_level_def_id(self.r.local_def_id(node_id), access_level)
110     }
111
112     fn set_access_level_def_id(
113         &mut self,
114         def_id: LocalDefId,
115         access_level: Option<AccessLevel>,
116     ) -> Option<AccessLevel> {
117         let old_level = self.r.access_levels.map.get(&def_id).copied();
118         if old_level < access_level {
119             self.r.access_levels.map.insert(def_id, access_level.unwrap());
120             self.changed = true;
121             access_level
122         } else {
123             old_level
124         }
125     }
126 }
127
128 impl<'r, 'ast> Visitor<'ast> for AccessLevelsVisitor<'ast, 'r> {
129     fn visit_item(&mut self, item: &'ast ast::Item) {
130         let inherited_item_level = match item.kind {
131             // Resolved in rustc_privacy when types are available
132             ast::ItemKind::Impl(..) => return,
133
134             // Only exported `macro_rules!` items are public, but they always are
135             ast::ItemKind::MacroDef(ref macro_def) if macro_def.macro_rules => {
136                 let is_macro_export =
137                     item.attrs.iter().any(|attr| attr.has_name(sym::macro_export));
138                 if is_macro_export { Some(AccessLevel::Public) } else { None }
139             }
140
141             // Foreign modules inherit level from parents.
142             ast::ItemKind::ForeignMod(..) => self.prev_level,
143
144             // Other `pub` items inherit levels from parents.
145             ast::ItemKind::ExternCrate(..)
146             | ast::ItemKind::Use(..)
147             | ast::ItemKind::Static(..)
148             | ast::ItemKind::Const(..)
149             | ast::ItemKind::Fn(..)
150             | ast::ItemKind::Mod(..)
151             | ast::ItemKind::GlobalAsm(..)
152             | ast::ItemKind::TyAlias(..)
153             | ast::ItemKind::Enum(..)
154             | ast::ItemKind::Struct(..)
155             | ast::ItemKind::Union(..)
156             | ast::ItemKind::Trait(..)
157             | ast::ItemKind::TraitAlias(..)
158             | ast::ItemKind::MacroDef(..) => {
159                 if item.vis.kind.is_pub() {
160                     self.prev_level
161                 } else {
162                     None
163                 }
164             }
165
166             // Should be unreachable at this stage
167             ast::ItemKind::MacCall(..) => panic!(
168                 "ast::ItemKind::MacCall encountered, this should not anymore appear at this stage"
169             ),
170         };
171
172         let access_level = self.set_access_level(item.id, inherited_item_level);
173
174         // Set access level of nested items.
175         // If it's a mod, also make the visitor walk all of its items
176         match item.kind {
177             ast::ItemKind::Mod(..) => {
178                 if access_level.is_some() {
179                     self.set_exports_access_level(self.r.local_def_id(item.id));
180                 }
181
182                 let orig_level = std::mem::replace(&mut self.prev_level, access_level);
183                 visit::walk_item(self, item);
184                 self.prev_level = orig_level;
185             }
186
187             ast::ItemKind::ForeignMod(ForeignMod { ref items, .. }) => {
188                 for nested in items {
189                     if nested.vis.kind.is_pub() {
190                         self.set_access_level(nested.id, access_level);
191                     }
192                 }
193             }
194             ast::ItemKind::Enum(EnumDef { ref variants }, _) => {
195                 for variant in variants {
196                     let variant_level = self.set_access_level(variant.id, access_level);
197                     if let Some(ctor_id) = variant.data.ctor_id() {
198                         self.set_access_level(ctor_id, access_level);
199                     }
200
201                     for field in variant.data.fields() {
202                         self.set_access_level(field.id, variant_level);
203                     }
204                 }
205             }
206             ast::ItemKind::Struct(ref def, _) | ast::ItemKind::Union(ref def, _) => {
207                 if let Some(ctor_id) = def.ctor_id() {
208                     self.set_access_level(ctor_id, access_level);
209                 }
210
211                 for field in def.fields() {
212                     if field.vis.kind.is_pub() {
213                         self.set_access_level(field.id, access_level);
214                     }
215                 }
216             }
217             ast::ItemKind::Trait(ref trait_kind) => {
218                 for nested in trait_kind.items.iter() {
219                     self.set_access_level(nested.id, access_level);
220                 }
221             }
222
223             ast::ItemKind::ExternCrate(..)
224             | ast::ItemKind::Use(..)
225             | ast::ItemKind::Static(..)
226             | ast::ItemKind::Const(..)
227             | ast::ItemKind::GlobalAsm(..)
228             | ast::ItemKind::TyAlias(..)
229             | ast::ItemKind::TraitAlias(..)
230             | ast::ItemKind::MacroDef(..)
231             | ast::ItemKind::Fn(..) => return,
232
233             // Unreachable kinds
234             ast::ItemKind::Impl(..) | ast::ItemKind::MacCall(..) => unreachable!(),
235         }
236     }
237 }