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