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