]> git.lizzy.rs Git - rust.git/blob - crates/hir/src/semantics/source_to_def.rs
Handle attribute macros in `descend_into_macros`
[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             let res: ChildContainer = match_ast! {
215                 match (container.value) {
216                     ast::Module(it) => {
217                         let def = self.module_to_def(container.with_value(it))?;
218                         def.into()
219                     },
220                     ast::Trait(it) => {
221                         let def = self.trait_to_def(container.with_value(it))?;
222                         def.into()
223                     },
224                     ast::Impl(it) => {
225                         let def = self.impl_to_def(container.with_value(it))?;
226                         def.into()
227                     },
228                     ast::Fn(it) => {
229                         let def = self.fn_to_def(container.with_value(it))?;
230                         DefWithBodyId::from(def).into()
231                     },
232                     ast::Struct(it) => {
233                         let def = self.struct_to_def(container.with_value(it))?;
234                         VariantId::from(def).into()
235                     },
236                     ast::Enum(it) => {
237                         let def = self.enum_to_def(container.with_value(it))?;
238                         def.into()
239                     },
240                     ast::Union(it) => {
241                         let def = self.union_to_def(container.with_value(it))?;
242                         VariantId::from(def).into()
243                     },
244                     ast::Static(it) => {
245                         let def = self.static_to_def(container.with_value(it))?;
246                         DefWithBodyId::from(def).into()
247                     },
248                     ast::Const(it) => {
249                         let def = self.const_to_def(container.with_value(it))?;
250                         DefWithBodyId::from(def).into()
251                     },
252                     ast::TypeAlias(it) => {
253                         let def = self.type_alias_to_def(container.with_value(it))?;
254                         def.into()
255                     },
256                     ast::Variant(it) => {
257                         let def = self.enum_variant_to_def(container.with_value(it))?;
258                         VariantId::from(def).into()
259                     },
260                     _ => continue,
261                 }
262             };
263             return Some(res);
264         }
265
266         let def = self.file_to_def(src.file_id.original_file(self.db.upcast())).get(0).copied()?;
267         Some(def.into())
268     }
269
270     fn find_generic_param_container(&mut self, src: InFile<&SyntaxNode>) -> Option<GenericDefId> {
271         for container in src.cloned().ancestors_with_macros(self.db.upcast()).skip(1) {
272             let res: GenericDefId = match_ast! {
273                 match (container.value) {
274                     ast::Fn(it) => self.fn_to_def(container.with_value(it))?.into(),
275                     ast::Struct(it) => self.struct_to_def(container.with_value(it))?.into(),
276                     ast::Enum(it) => self.enum_to_def(container.with_value(it))?.into(),
277                     ast::Trait(it) => self.trait_to_def(container.with_value(it))?.into(),
278                     ast::TypeAlias(it) => self.type_alias_to_def(container.with_value(it))?.into(),
279                     ast::Impl(it) => self.impl_to_def(container.with_value(it))?.into(),
280                     _ => continue,
281                 }
282             };
283             return Some(res);
284         }
285         None
286     }
287
288     fn find_pat_or_label_container(&mut self, src: InFile<&SyntaxNode>) -> Option<DefWithBodyId> {
289         for container in src.cloned().ancestors_with_macros(self.db.upcast()).skip(1) {
290             let res: DefWithBodyId = match_ast! {
291                 match (container.value) {
292                     ast::Const(it) => self.const_to_def(container.with_value(it))?.into(),
293                     ast::Static(it) => self.static_to_def(container.with_value(it))?.into(),
294                     ast::Fn(it) => self.fn_to_def(container.with_value(it))?.into(),
295                     _ => continue,
296                 }
297             };
298             return Some(res);
299         }
300         None
301     }
302 }
303
304 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
305 pub(crate) enum ChildContainer {
306     DefWithBodyId(DefWithBodyId),
307     ModuleId(ModuleId),
308     TraitId(TraitId),
309     ImplId(ImplId),
310     EnumId(EnumId),
311     VariantId(VariantId),
312     TypeAliasId(TypeAliasId),
313     /// XXX: this might be the same def as, for example an `EnumId`. However,
314     /// here the children are generic parameters, and not, eg enum variants.
315     GenericDefId(GenericDefId),
316 }
317 impl_from! {
318     DefWithBodyId,
319     ModuleId,
320     TraitId,
321     ImplId,
322     EnumId,
323     VariantId,
324     TypeAliasId,
325     GenericDefId
326     for ChildContainer
327 }
328
329 impl ChildContainer {
330     fn child_by_source(self, db: &dyn HirDatabase) -> DynMap {
331         let db = db.upcast();
332         match self {
333             ChildContainer::DefWithBodyId(it) => it.child_by_source(db),
334             ChildContainer::ModuleId(it) => it.child_by_source(db),
335             ChildContainer::TraitId(it) => it.child_by_source(db),
336             ChildContainer::ImplId(it) => it.child_by_source(db),
337             ChildContainer::EnumId(it) => it.child_by_source(db),
338             ChildContainer::VariantId(it) => it.child_by_source(db),
339             ChildContainer::TypeAliasId(_) => DynMap::default(),
340             ChildContainer::GenericDefId(it) => it.child_by_source(db),
341         }
342     }
343 }