]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/visibility.rs
parameters.split_last()
[rust.git] / crates / hir_def / src / visibility.rs
1 //! Defines hir-level representation of visibility (e.g. `pub` and `pub(crate)`).
2
3 use std::sync::Arc;
4
5 use hir_expand::{hygiene::Hygiene, InFile};
6 use la_arena::ArenaMap;
7 use syntax::ast;
8
9 use crate::{
10     db::DefDatabase,
11     nameres::DefMap,
12     path::{ModPath, PathKind},
13     resolver::HasResolver,
14     FunctionId, HasModule, LocalFieldId, ModuleId, VariantId,
15 };
16
17 /// Visibility of an item, not yet resolved.
18 #[derive(Debug, Clone, PartialEq, Eq)]
19 pub enum RawVisibility {
20     /// `pub(in module)`, `pub(crate)` or `pub(super)`. Also private, which is
21     /// equivalent to `pub(self)`.
22     Module(ModPath),
23     /// `pub`.
24     Public,
25 }
26
27 impl RawVisibility {
28     pub(crate) fn private() -> RawVisibility {
29         RawVisibility::Module(ModPath::from_kind(PathKind::Super(0)))
30     }
31
32     pub(crate) fn from_ast(
33         db: &dyn DefDatabase,
34         node: InFile<Option<ast::Visibility>>,
35     ) -> RawVisibility {
36         Self::from_ast_with_hygiene(db, node.value, &Hygiene::new(db.upcast(), node.file_id))
37     }
38
39     pub(crate) fn from_ast_with_hygiene(
40         db: &dyn DefDatabase,
41         node: Option<ast::Visibility>,
42         hygiene: &Hygiene,
43     ) -> RawVisibility {
44         Self::from_ast_with_hygiene_and_default(db, node, RawVisibility::private(), hygiene)
45     }
46
47     pub(crate) fn from_ast_with_hygiene_and_default(
48         db: &dyn DefDatabase,
49         node: Option<ast::Visibility>,
50         default: RawVisibility,
51         hygiene: &Hygiene,
52     ) -> RawVisibility {
53         let node = match node {
54             None => return default,
55             Some(node) => node,
56         };
57         match node.kind() {
58             ast::VisibilityKind::In(path) => {
59                 let path = ModPath::from_src(db.upcast(), path, hygiene);
60                 let path = match path {
61                     None => return RawVisibility::private(),
62                     Some(path) => path,
63                 };
64                 RawVisibility::Module(path)
65             }
66             ast::VisibilityKind::PubCrate => {
67                 let path = ModPath::from_kind(PathKind::Crate);
68                 RawVisibility::Module(path)
69             }
70             ast::VisibilityKind::PubSuper => {
71                 let path = ModPath::from_kind(PathKind::Super(1));
72                 RawVisibility::Module(path)
73             }
74             ast::VisibilityKind::PubSelf => {
75                 let path = ModPath::from_kind(PathKind::Plain);
76                 RawVisibility::Module(path)
77             }
78             ast::VisibilityKind::Pub => RawVisibility::Public,
79         }
80     }
81
82     pub fn resolve(
83         &self,
84         db: &dyn DefDatabase,
85         resolver: &crate::resolver::Resolver,
86     ) -> Visibility {
87         // we fall back to public visibility (i.e. fail open) if the path can't be resolved
88         resolver.resolve_visibility(db, self).unwrap_or(Visibility::Public)
89     }
90 }
91
92 /// Visibility of an item, with the path resolved.
93 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
94 pub enum Visibility {
95     /// Visibility is restricted to a certain module.
96     Module(ModuleId),
97     /// Visibility is unrestricted.
98     Public,
99 }
100
101 impl Visibility {
102     pub fn is_visible_from(self, db: &dyn DefDatabase, from_module: ModuleId) -> bool {
103         let to_module = match self {
104             Visibility::Module(m) => m,
105             Visibility::Public => return true,
106         };
107         // if they're not in the same crate, it can't be visible
108         if from_module.krate != to_module.krate {
109             return false;
110         }
111         let def_map = from_module.def_map(db);
112         self.is_visible_from_def_map(db, &def_map, from_module.local_id)
113     }
114
115     pub(crate) fn is_visible_from_other_crate(self) -> bool {
116         match self {
117             Visibility::Module(_) => false,
118             Visibility::Public => true,
119         }
120     }
121
122     pub(crate) fn is_visible_from_def_map(
123         self,
124         db: &dyn DefDatabase,
125         def_map: &DefMap,
126         mut from_module: crate::LocalModuleId,
127     ) -> bool {
128         let mut to_module = match self {
129             Visibility::Module(m) => m,
130             Visibility::Public => return true,
131         };
132
133         // `to_module` might be the root module of a block expression. Those have the same
134         // visibility as the containing module (even though no items are directly nameable from
135         // there, getting this right is important for method resolution).
136         // In that case, we adjust the visibility of `to_module` to point to the containing module.
137         // Additional complication: `to_module` might be in `from_module`'s `DefMap`, which we're
138         // currently computing, so we must not call the `def_map` query for it.
139         let arc;
140         let to_module_def_map =
141             if to_module.krate == def_map.krate() && to_module.block == def_map.block_id() {
142                 cov_mark::hit!(is_visible_from_same_block_def_map);
143                 def_map
144             } else {
145                 arc = to_module.def_map(db);
146                 &arc
147             };
148         let is_block_root = match to_module.block {
149             Some(_) => to_module_def_map[to_module.local_id].parent.is_none(),
150             None => false,
151         };
152         if is_block_root {
153             to_module = to_module_def_map.containing_module(to_module.local_id).unwrap();
154         }
155
156         // from_module needs to be a descendant of to_module
157         let mut def_map = def_map;
158         let mut parent_arc;
159         loop {
160             if def_map.module_id(from_module) == to_module {
161                 return true;
162             }
163             match def_map[from_module].parent {
164                 Some(parent) => {
165                     from_module = parent;
166                 }
167                 None => {
168                     match def_map.parent() {
169                         Some(module) => {
170                             parent_arc = module.def_map(db);
171                             def_map = &*parent_arc;
172                             from_module = module.local_id;
173                         }
174                         None => {
175                             // Reached the root module, nothing left to check.
176                             return false;
177                         }
178                     }
179                 }
180             }
181         }
182     }
183
184     /// Returns the most permissive visibility of `self` and `other`.
185     ///
186     /// If there is no subset relation between `self` and `other`, returns `None` (ie. they're only
187     /// visible in unrelated modules).
188     pub(crate) fn max(self, other: Visibility, def_map: &DefMap) -> Option<Visibility> {
189         match (self, other) {
190             (Visibility::Module(_) | Visibility::Public, Visibility::Public)
191             | (Visibility::Public, Visibility::Module(_)) => Some(Visibility::Public),
192             (Visibility::Module(mod_a), Visibility::Module(mod_b)) => {
193                 if mod_a.krate != mod_b.krate {
194                     return None;
195                 }
196
197                 let mut a_ancestors = std::iter::successors(Some(mod_a.local_id), |m| {
198                     let parent_id = def_map[*m].parent?;
199                     Some(parent_id)
200                 });
201                 let mut b_ancestors = std::iter::successors(Some(mod_b.local_id), |m| {
202                     let parent_id = def_map[*m].parent?;
203                     Some(parent_id)
204                 });
205
206                 if a_ancestors.any(|m| m == mod_b.local_id) {
207                     // B is above A
208                     return Some(Visibility::Module(mod_b));
209                 }
210
211                 if b_ancestors.any(|m| m == mod_a.local_id) {
212                     // A is above B
213                     return Some(Visibility::Module(mod_a));
214                 }
215
216                 None
217             }
218         }
219     }
220 }
221
222 /// Resolve visibility of all specific fields of a struct or union variant.
223 pub(crate) fn field_visibilities_query(
224     db: &dyn DefDatabase,
225     variant_id: VariantId,
226 ) -> Arc<ArenaMap<LocalFieldId, Visibility>> {
227     let var_data = match variant_id {
228         VariantId::StructId(it) => db.struct_data(it).variant_data.clone(),
229         VariantId::UnionId(it) => db.union_data(it).variant_data.clone(),
230         VariantId::EnumVariantId(it) => {
231             db.enum_data(it.parent).variants[it.local_id].variant_data.clone()
232         }
233     };
234     let resolver = variant_id.module(db).resolver(db);
235     let mut res = ArenaMap::default();
236     for (field_id, field_data) in var_data.fields().iter() {
237         res.insert(field_id, field_data.visibility.resolve(db, &resolver))
238     }
239     Arc::new(res)
240 }
241
242 /// Resolve visibility of a function.
243 pub(crate) fn function_visibility_query(db: &dyn DefDatabase, def: FunctionId) -> Visibility {
244     let resolver = def.resolver(db);
245     db.function_data(def).visibility.resolve(db, &resolver)
246 }