]> git.lizzy.rs Git - rust.git/blob - crates/hir/src/semantics/source_to_def.rs
Merge #9187
[rust.git] / crates / hir / src / semantics / source_to_def.rs
1 //! Maps *syntax* of various definitions to their semantic ids.
2
3 use base_db::FileId;
4 use hir_def::{
5     child_by_source::ChildBySource,
6     dyn_map::DynMap,
7     expr::{LabelId, PatId},
8     keys::{self, Key},
9     ConstId, ConstParamId, DefWithBodyId, EnumId, EnumVariantId, FieldId, FunctionId, GenericDefId,
10     ImplId, LifetimeParamId, ModuleId, StaticId, StructId, TraitId, TypeAliasId, TypeParamId,
11     UnionId, VariantId,
12 };
13 use hir_expand::{name::AsName, AstId, MacroCallId, MacroDefKind};
14 use rustc_hash::FxHashMap;
15 use smallvec::SmallVec;
16 use stdx::impl_from;
17 use syntax::{
18     ast::{self, NameOwner},
19     match_ast, AstNode, SyntaxNode,
20 };
21
22 use crate::{db::HirDatabase, InFile, MacroDefId};
23
24 pub(super) type SourceToDefCache = FxHashMap<ChildContainer, DynMap>;
25
26 pub(super) struct SourceToDefCtx<'a, 'b> {
27     pub(super) db: &'b dyn HirDatabase,
28     pub(super) cache: &'a mut SourceToDefCache,
29 }
30
31 impl SourceToDefCtx<'_, '_> {
32     pub(super) fn file_to_def(&mut self, file: FileId) -> SmallVec<[ModuleId; 1]> {
33         let _p = profile::span("SourceBinder::to_module_def");
34         let mut mods = SmallVec::new();
35         for &crate_id in self.db.relevant_crates(file).iter() {
36             // FIXME: inner items
37             let crate_def_map = self.db.crate_def_map(crate_id);
38             mods.extend(
39                 crate_def_map
40                     .modules_for_file(file)
41                     .map(|local_id| crate_def_map.module_id(local_id)),
42             )
43         }
44         mods
45     }
46
47     pub(super) fn module_to_def(&mut self, src: InFile<ast::Module>) -> Option<ModuleId> {
48         let _p = profile::span("module_to_def");
49         let parent_declaration = src
50             .as_ref()
51             .map(|it| it.syntax())
52             .cloned()
53             .ancestors_with_macros(self.db.upcast())
54             .skip(1)
55             .find_map(|it| {
56                 let m = ast::Module::cast(it.value.clone())?;
57                 Some(it.with_value(m))
58             });
59
60         let parent_module = match parent_declaration {
61             Some(parent_declaration) => self.module_to_def(parent_declaration),
62             None => {
63                 let file_id = src.file_id.original_file(self.db.upcast());
64                 self.file_to_def(file_id).get(0).copied()
65             }
66         }?;
67
68         let child_name = src.value.name()?.as_name();
69         let def_map = parent_module.def_map(self.db.upcast());
70         let child_id = *def_map[parent_module.local_id].children.get(&child_name)?;
71         Some(def_map.module_id(child_id))
72     }
73
74     pub(super) fn source_file_to_def(&mut self, src: InFile<ast::SourceFile>) -> Option<ModuleId> {
75         let _p = profile::span("source_file_to_def");
76         let file_id = src.file_id.original_file(self.db.upcast());
77         self.file_to_def(file_id).get(0).copied()
78     }
79
80     pub(super) fn trait_to_def(&mut self, src: InFile<ast::Trait>) -> Option<TraitId> {
81         self.to_def(src, keys::TRAIT)
82     }
83     pub(super) fn impl_to_def(&mut self, src: InFile<ast::Impl>) -> Option<ImplId> {
84         self.to_def(src, keys::IMPL)
85     }
86     pub(super) fn fn_to_def(&mut self, src: InFile<ast::Fn>) -> Option<FunctionId> {
87         self.to_def(src, keys::FUNCTION)
88     }
89     pub(super) fn struct_to_def(&mut self, src: InFile<ast::Struct>) -> Option<StructId> {
90         self.to_def(src, keys::STRUCT)
91     }
92     pub(super) fn enum_to_def(&mut self, src: InFile<ast::Enum>) -> Option<EnumId> {
93         self.to_def(src, keys::ENUM)
94     }
95     pub(super) fn union_to_def(&mut self, src: InFile<ast::Union>) -> Option<UnionId> {
96         self.to_def(src, keys::UNION)
97     }
98     pub(super) fn static_to_def(&mut self, src: InFile<ast::Static>) -> Option<StaticId> {
99         self.to_def(src, keys::STATIC)
100     }
101     pub(super) fn const_to_def(&mut self, src: InFile<ast::Const>) -> Option<ConstId> {
102         self.to_def(src, keys::CONST)
103     }
104     pub(super) fn type_alias_to_def(&mut self, src: InFile<ast::TypeAlias>) -> Option<TypeAliasId> {
105         self.to_def(src, keys::TYPE_ALIAS)
106     }
107     pub(super) fn record_field_to_def(&mut self, src: InFile<ast::RecordField>) -> Option<FieldId> {
108         self.to_def(src, keys::RECORD_FIELD)
109     }
110     pub(super) fn tuple_field_to_def(&mut self, src: InFile<ast::TupleField>) -> Option<FieldId> {
111         self.to_def(src, keys::TUPLE_FIELD)
112     }
113     pub(super) fn enum_variant_to_def(
114         &mut self,
115         src: InFile<ast::Variant>,
116     ) -> Option<EnumVariantId> {
117         self.to_def(src, keys::VARIANT)
118     }
119     pub(super) fn bind_pat_to_def(
120         &mut self,
121         src: InFile<ast::IdentPat>,
122     ) -> Option<(DefWithBodyId, PatId)> {
123         let container = self.find_pat_or_label_container(src.as_ref().map(|it| it.syntax()))?;
124         let (_body, source_map) = self.db.body_with_source_map(container);
125         let src = src.map(ast::Pat::from);
126         let pat_id = source_map.node_pat(src.as_ref())?;
127         Some((container, pat_id))
128     }
129     pub(super) fn self_param_to_def(
130         &mut self,
131         src: InFile<ast::SelfParam>,
132     ) -> Option<(DefWithBodyId, PatId)> {
133         let container = self.find_pat_or_label_container(src.as_ref().map(|it| it.syntax()))?;
134         let (_body, source_map) = self.db.body_with_source_map(container);
135         let pat_id = source_map.node_self_param(src.as_ref())?;
136         Some((container, pat_id))
137     }
138     pub(super) fn label_to_def(
139         &mut self,
140         src: InFile<ast::Label>,
141     ) -> Option<(DefWithBodyId, LabelId)> {
142         let container = self.find_pat_or_label_container(src.as_ref().map(|it| it.syntax()))?;
143         let (_body, source_map) = self.db.body_with_source_map(container);
144         let label_id = source_map.node_label(src.as_ref())?;
145         Some((container, label_id))
146     }
147
148     pub(super) fn item_to_macro_call(&mut self, src: InFile<ast::Item>) -> Option<MacroCallId> {
149         let map = self.dyn_map(src.as_ref())?;
150         map[keys::ATTR_MACRO].get(&src).copied()
151     }
152
153     fn to_def<Ast: AstNode + 'static, ID: Copy + 'static>(
154         &mut self,
155         src: InFile<Ast>,
156         key: Key<Ast, ID>,
157     ) -> Option<ID> {
158         self.dyn_map(src.as_ref())?[key].get(&src).copied()
159     }
160
161     fn dyn_map<Ast: AstNode + 'static>(&mut self, src: InFile<&Ast>) -> Option<&DynMap> {
162         let container = self.find_container(src.map(|it| it.syntax()))?;
163         let db = self.db;
164         let dyn_map =
165             &*self.cache.entry(container).or_insert_with(|| container.child_by_source(db));
166         Some(dyn_map)
167     }
168
169     pub(super) fn type_param_to_def(&mut self, src: InFile<ast::TypeParam>) -> Option<TypeParamId> {
170         let container: ChildContainer =
171             self.find_generic_param_container(src.as_ref().map(|it| it.syntax()))?.into();
172         let db = self.db;
173         let dyn_map =
174             &*self.cache.entry(container).or_insert_with(|| container.child_by_source(db));
175         dyn_map[keys::TYPE_PARAM].get(&src).copied()
176     }
177
178     pub(super) fn lifetime_param_to_def(
179         &mut self,
180         src: InFile<ast::LifetimeParam>,
181     ) -> Option<LifetimeParamId> {
182         let container: ChildContainer =
183             self.find_generic_param_container(src.as_ref().map(|it| it.syntax()))?.into();
184         let db = self.db;
185         let dyn_map =
186             &*self.cache.entry(container).or_insert_with(|| container.child_by_source(db));
187         dyn_map[keys::LIFETIME_PARAM].get(&src).copied()
188     }
189
190     pub(super) fn const_param_to_def(
191         &mut self,
192         src: InFile<ast::ConstParam>,
193     ) -> Option<ConstParamId> {
194         let container: ChildContainer =
195             self.find_generic_param_container(src.as_ref().map(|it| it.syntax()))?.into();
196         let db = self.db;
197         let dyn_map =
198             &*self.cache.entry(container).or_insert_with(|| container.child_by_source(db));
199         dyn_map[keys::CONST_PARAM].get(&src).copied()
200     }
201
202     // FIXME: use DynMap as well?
203     pub(super) fn macro_to_def(&mut self, src: InFile<ast::Macro>) -> Option<MacroDefId> {
204         let file_ast_id = self.db.ast_id_map(src.file_id).ast_id(&src.value);
205         let ast_id = AstId::new(src.file_id, file_ast_id.upcast());
206         let kind = MacroDefKind::Declarative(ast_id);
207         let file_id = src.file_id.original_file(self.db.upcast());
208         let krate = self.file_to_def(file_id).get(0).copied()?.krate();
209         Some(MacroDefId { krate, kind, local_inner: false })
210     }
211
212     pub(super) fn find_container(&mut self, src: InFile<&SyntaxNode>) -> Option<ChildContainer> {
213         for container in src.cloned().ancestors_with_macros(self.db.upcast()).skip(1) {
214             if let Some(res) = self.container_to_def(container) {
215                 return Some(res);
216             }
217         }
218
219         let def = self.file_to_def(src.file_id.original_file(self.db.upcast())).get(0).copied()?;
220         Some(def.into())
221     }
222
223     fn container_to_def(&mut self, container: InFile<SyntaxNode>) -> Option<ChildContainer> {
224         let cont = match_ast! {
225             match (container.value) {
226                 ast::Module(it) => {
227                     let def = self.module_to_def(container.with_value(it))?;
228                     def.into()
229                 },
230                 ast::Trait(it) => {
231                     let def = self.trait_to_def(container.with_value(it))?;
232                     def.into()
233                 },
234                 ast::Impl(it) => {
235                     let def = self.impl_to_def(container.with_value(it))?;
236                     def.into()
237                 },
238                 ast::Fn(it) => {
239                     let def = self.fn_to_def(container.with_value(it))?;
240                     DefWithBodyId::from(def).into()
241                 },
242                 ast::Struct(it) => {
243                     let def = self.struct_to_def(container.with_value(it))?;
244                     VariantId::from(def).into()
245                 },
246                 ast::Enum(it) => {
247                     let def = self.enum_to_def(container.with_value(it))?;
248                     def.into()
249                 },
250                 ast::Union(it) => {
251                     let def = self.union_to_def(container.with_value(it))?;
252                     VariantId::from(def).into()
253                 },
254                 ast::Static(it) => {
255                     let def = self.static_to_def(container.with_value(it))?;
256                     DefWithBodyId::from(def).into()
257                 },
258                 ast::Const(it) => {
259                     let def = self.const_to_def(container.with_value(it))?;
260                     DefWithBodyId::from(def).into()
261                 },
262                 ast::TypeAlias(it) => {
263                     let def = self.type_alias_to_def(container.with_value(it))?;
264                     def.into()
265                 },
266                 ast::Variant(it) => {
267                     let def = self.enum_variant_to_def(container.with_value(it))?;
268                     VariantId::from(def).into()
269                 },
270                 _ => return None,
271             }
272         };
273         Some(cont)
274     }
275
276     fn find_generic_param_container(&mut self, src: InFile<&SyntaxNode>) -> Option<GenericDefId> {
277         for container in src.cloned().ancestors_with_macros(self.db.upcast()).skip(1) {
278             let res: GenericDefId = match_ast! {
279                 match (container.value) {
280                     ast::Fn(it) => self.fn_to_def(container.with_value(it))?.into(),
281                     ast::Struct(it) => self.struct_to_def(container.with_value(it))?.into(),
282                     ast::Enum(it) => self.enum_to_def(container.with_value(it))?.into(),
283                     ast::Trait(it) => self.trait_to_def(container.with_value(it))?.into(),
284                     ast::TypeAlias(it) => self.type_alias_to_def(container.with_value(it))?.into(),
285                     ast::Impl(it) => self.impl_to_def(container.with_value(it))?.into(),
286                     _ => continue,
287                 }
288             };
289             return Some(res);
290         }
291         None
292     }
293
294     fn find_pat_or_label_container(&mut self, src: InFile<&SyntaxNode>) -> Option<DefWithBodyId> {
295         for container in src.cloned().ancestors_with_macros(self.db.upcast()).skip(1) {
296             let res: DefWithBodyId = match_ast! {
297                 match (container.value) {
298                     ast::Const(it) => self.const_to_def(container.with_value(it))?.into(),
299                     ast::Static(it) => self.static_to_def(container.with_value(it))?.into(),
300                     ast::Fn(it) => self.fn_to_def(container.with_value(it))?.into(),
301                     _ => continue,
302                 }
303             };
304             return Some(res);
305         }
306         None
307     }
308 }
309
310 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
311 pub(crate) enum ChildContainer {
312     DefWithBodyId(DefWithBodyId),
313     ModuleId(ModuleId),
314     TraitId(TraitId),
315     ImplId(ImplId),
316     EnumId(EnumId),
317     VariantId(VariantId),
318     TypeAliasId(TypeAliasId),
319     /// XXX: this might be the same def as, for example an `EnumId`. However,
320     /// here the children are generic parameters, and not, eg enum variants.
321     GenericDefId(GenericDefId),
322 }
323 impl_from! {
324     DefWithBodyId,
325     ModuleId,
326     TraitId,
327     ImplId,
328     EnumId,
329     VariantId,
330     TypeAliasId,
331     GenericDefId
332     for ChildContainer
333 }
334
335 impl ChildContainer {
336     fn child_by_source(self, db: &dyn HirDatabase) -> DynMap {
337         let db = db.upcast();
338         match self {
339             ChildContainer::DefWithBodyId(it) => it.child_by_source(db),
340             ChildContainer::ModuleId(it) => it.child_by_source(db),
341             ChildContainer::TraitId(it) => it.child_by_source(db),
342             ChildContainer::ImplId(it) => it.child_by_source(db),
343             ChildContainer::EnumId(it) => it.child_by_source(db),
344             ChildContainer::VariantId(it) => it.child_by_source(db),
345             ChildContainer::TypeAliasId(_) => DynMap::default(),
346             ChildContainer::GenericDefId(it) => it.child_by_source(db),
347         }
348     }
349 }