]> git.lizzy.rs Git - rust.git/blob - crates/hir/src/semantics/source_to_def.rs
Add ConstParams to the HIR
[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, 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_or_label_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     pub(super) fn label_to_def(
118         &mut self,
119         src: InFile<ast::Label>,
120     ) -> Option<(DefWithBodyId, LabelId)> {
121         let container = self.find_pat_or_label_container(src.as_ref().map(|it| it.syntax()))?;
122         let (_body, source_map) = self.db.body_with_source_map(container);
123         let label_id = source_map.node_label(src.as_ref())?;
124         Some((container, label_id))
125     }
126
127     fn to_def<Ast: AstNode + 'static, ID: Copy + 'static>(
128         &mut self,
129         src: InFile<Ast>,
130         key: Key<Ast, ID>,
131     ) -> Option<ID> {
132         let container = self.find_container(src.as_ref().map(|it| it.syntax()))?;
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[key].get(&src).copied()
137     }
138
139     pub(super) fn type_param_to_def(&mut self, src: InFile<ast::TypeParam>) -> Option<TypeParamId> {
140         let container: ChildContainer =
141             self.find_generic_param_container(src.as_ref().map(|it| it.syntax()))?.into();
142         let db = self.db;
143         let dyn_map =
144             &*self.cache.entry(container).or_insert_with(|| container.child_by_source(db));
145         dyn_map[keys::TYPE_PARAM].get(&src).copied()
146     }
147
148     pub(super) fn lifetime_param_to_def(
149         &mut self,
150         src: InFile<ast::LifetimeParam>,
151     ) -> Option<LifetimeParamId> {
152         let container: ChildContainer =
153             self.find_generic_param_container(src.as_ref().map(|it| it.syntax()))?.into();
154         let db = self.db;
155         let dyn_map =
156             &*self.cache.entry(container).or_insert_with(|| container.child_by_source(db));
157         dyn_map[keys::LIFETIME_PARAM].get(&src).copied()
158     }
159
160     pub(super) fn const_param_to_def(
161         &mut self,
162         src: InFile<ast::ConstParam>,
163     ) -> Option<ConstParamId> {
164         let container: ChildContainer =
165             self.find_generic_param_container(src.as_ref().map(|it| it.syntax()))?.into();
166         let db = self.db;
167         let dyn_map =
168             &*self.cache.entry(container).or_insert_with(|| container.child_by_source(db));
169         dyn_map[keys::CONST_PARAM].get(&src).copied()
170     }
171
172     // FIXME: use DynMap as well?
173     pub(super) fn macro_rules_to_def(
174         &mut self,
175         src: InFile<ast::MacroRules>,
176     ) -> Option<MacroDefId> {
177         let kind = MacroDefKind::Declarative;
178         let file_id = src.file_id.original_file(self.db.upcast());
179         let krate = self.file_to_def(file_id)?.krate;
180         let file_ast_id = self.db.ast_id_map(src.file_id).ast_id(&src.value);
181         let ast_id = Some(AstId::new(src.file_id, file_ast_id.upcast()));
182         Some(MacroDefId { krate, ast_id, kind, local_inner: false })
183     }
184
185     pub(super) fn find_container(&mut self, src: InFile<&SyntaxNode>) -> Option<ChildContainer> {
186         for container in src.cloned().ancestors_with_macros(self.db.upcast()).skip(1) {
187             let res: ChildContainer = match_ast! {
188                 match (container.value) {
189                     ast::Module(it) => {
190                         let def = self.module_to_def(container.with_value(it))?;
191                         def.into()
192                     },
193                     ast::Trait(it) => {
194                         let def = self.trait_to_def(container.with_value(it))?;
195                         def.into()
196                     },
197                     ast::Impl(it) => {
198                         let def = self.impl_to_def(container.with_value(it))?;
199                         def.into()
200                     },
201                     ast::Fn(it) => {
202                         let def = self.fn_to_def(container.with_value(it))?;
203                         DefWithBodyId::from(def).into()
204                     },
205                     ast::Struct(it) => {
206                         let def = self.struct_to_def(container.with_value(it))?;
207                         VariantId::from(def).into()
208                     },
209                     ast::Enum(it) => {
210                         let def = self.enum_to_def(container.with_value(it))?;
211                         def.into()
212                     },
213                     ast::Union(it) => {
214                         let def = self.union_to_def(container.with_value(it))?;
215                         VariantId::from(def).into()
216                     },
217                     ast::Static(it) => {
218                         let def = self.static_to_def(container.with_value(it))?;
219                         DefWithBodyId::from(def).into()
220                     },
221                     ast::Const(it) => {
222                         let def = self.const_to_def(container.with_value(it))?;
223                         DefWithBodyId::from(def).into()
224                     },
225                     ast::TypeAlias(it) => {
226                         let def = self.type_alias_to_def(container.with_value(it))?;
227                         def.into()
228                     },
229                     ast::Variant(it) => {
230                         let def = self.enum_variant_to_def(container.with_value(it))?;
231                         VariantId::from(def).into()
232                     },
233                     _ => continue,
234                 }
235             };
236             return Some(res);
237         }
238
239         let def = self.file_to_def(src.file_id.original_file(self.db.upcast()))?;
240         Some(def.into())
241     }
242
243     fn find_generic_param_container(&mut self, src: InFile<&SyntaxNode>) -> Option<GenericDefId> {
244         for container in src.cloned().ancestors_with_macros(self.db.upcast()).skip(1) {
245             let res: GenericDefId = match_ast! {
246                 match (container.value) {
247                     ast::Fn(it) => self.fn_to_def(container.with_value(it))?.into(),
248                     ast::Struct(it) => self.struct_to_def(container.with_value(it))?.into(),
249                     ast::Enum(it) => self.enum_to_def(container.with_value(it))?.into(),
250                     ast::Trait(it) => self.trait_to_def(container.with_value(it))?.into(),
251                     ast::TypeAlias(it) => self.type_alias_to_def(container.with_value(it))?.into(),
252                     ast::Impl(it) => self.impl_to_def(container.with_value(it))?.into(),
253                     _ => continue,
254                 }
255             };
256             return Some(res);
257         }
258         None
259     }
260
261     fn find_pat_or_label_container(&mut self, src: InFile<&SyntaxNode>) -> Option<DefWithBodyId> {
262         for container in src.cloned().ancestors_with_macros(self.db.upcast()).skip(1) {
263             let res: DefWithBodyId = match_ast! {
264                 match (container.value) {
265                     ast::Const(it) => self.const_to_def(container.with_value(it))?.into(),
266                     ast::Static(it) => self.static_to_def(container.with_value(it))?.into(),
267                     ast::Fn(it) => self.fn_to_def(container.with_value(it))?.into(),
268                     _ => continue,
269                 }
270             };
271             return Some(res);
272         }
273         None
274     }
275 }
276
277 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
278 pub(crate) enum ChildContainer {
279     DefWithBodyId(DefWithBodyId),
280     ModuleId(ModuleId),
281     TraitId(TraitId),
282     ImplId(ImplId),
283     EnumId(EnumId),
284     VariantId(VariantId),
285     TypeAliasId(TypeAliasId),
286     /// XXX: this might be the same def as, for example an `EnumId`. However,
287     /// here the children are generic parameters, and not, eg enum variants.
288     GenericDefId(GenericDefId),
289 }
290 impl_from! {
291     DefWithBodyId,
292     ModuleId,
293     TraitId,
294     ImplId,
295     EnumId,
296     VariantId,
297     TypeAliasId,
298     GenericDefId
299     for ChildContainer
300 }
301
302 impl ChildContainer {
303     fn child_by_source(self, db: &dyn HirDatabase) -> DynMap {
304         let db = db.upcast();
305         match self {
306             ChildContainer::DefWithBodyId(it) => it.child_by_source(db),
307             ChildContainer::ModuleId(it) => it.child_by_source(db),
308             ChildContainer::TraitId(it) => it.child_by_source(db),
309             ChildContainer::ImplId(it) => it.child_by_source(db),
310             ChildContainer::EnumId(it) => it.child_by_source(db),
311             ChildContainer::VariantId(it) => it.child_by_source(db),
312             ChildContainer::TypeAliasId(_) => DynMap::default(),
313             ChildContainer::GenericDefId(it) => it.child_by_source(db),
314         }
315     }
316 }