]> git.lizzy.rs Git - rust.git/blob - crates/hir/src/semantics/source_to_def.rs
495c84e65f43e0a73a9a5d48f6beff778084523a
[rust.git] / crates / hir / src / semantics / source_to_def.rs
1 //! Maps *syntax* of various definitions to their semantic ids.
2 //!
3 //! This is a very interesting module, and, in some sense, can be considered the
4 //! heart of the IDE parts of rust-analyzer.
5 //!
6 //! This module solves the following problem:
7 //!
8 //!     Given a piece of syntax, find the corresponding semantic definition (def).
9 //!
10 //! This problem is a part of more-or-less every IDE feature implemented. Every
11 //! IDE functionality (like goto to definition), conceptually starts with a
12 //! specific cursor position in a file. Starting with this text offset, we first
13 //! figure out what syntactic construct are we at: is this a pattern, an
14 //! expression, an item definition.
15 //!
16 //! Knowing only the syntax gives us relatively little info. For example,
17 //! looking at the syntax of the function we can realise that it is a part of an
18 //! `impl` block, but we won't be able to tell what trait function the current
19 //! function overrides, and whether it does that correctly. For that, we need to
20 //! go from [`ast::Fn`] to [`crate::Function`], and that's exactly what this
21 //! module does.
22 //!
23 //! As syntax trees are values and don't know their place of origin/identity,
24 //! this module also requires [`InFile`] wrappers to understand which specific
25 //! real or macro-expanded file the tree comes from.
26 //!
27 //! The actual algorithm to resolve syntax to def is curious in two aspects:
28 //!
29 //!     * It is recursive
30 //!     * It uses the inverse algorithm (what is the syntax for this def?)
31 //!
32 //! Specifically, the algorithm goes like this:
33 //!
34 //!     1. Find the syntactic container for the syntax. For example, field's
35 //!        container is the struct, and structs container is a module.
36 //!     2. Recursively get the def corresponding to container.
37 //!     3. Ask the container def for all child defs. These child defs contain
38 //!        the answer and answer's siblings.
39 //!     4. For each child def, ask for it's source.
40 //!     5. The child def whose source is the syntax node we've started with
41 //!        is the answer.
42 //!
43 //! It's interesting that both Roslyn and Kotlin contain very similar code
44 //! shape.
45 //!
46 //! Let's take a look at Roslyn:
47 //!
48 //!   <https://github.com/dotnet/roslyn/blob/36a0c338d6621cc5fe34b79d414074a95a6a489c/src/Compilers/CSharp/Portable/Compilation/SyntaxTreeSemanticModel.cs#L1403-L1429>
49 //!   <https://sourceroslyn.io/#Microsoft.CodeAnalysis.CSharp/Compilation/SyntaxTreeSemanticModel.cs,1403>
50 //!
51 //! The `GetDeclaredType` takes `Syntax` as input, and returns `Symbol` as
52 //! output. First, it retrieves a `Symbol` for parent `Syntax`:
53 //!
54 //! * <https://sourceroslyn.io/#Microsoft.CodeAnalysis.CSharp/Compilation/SyntaxTreeSemanticModel.cs,1423>
55 //!
56 //! Then, it iterates parent symbol's children, looking for one which has the
57 //! same text span as the original node:
58 //!
59 //!   <https://sourceroslyn.io/#Microsoft.CodeAnalysis.CSharp/Compilation/SyntaxTreeSemanticModel.cs,1786>
60 //!
61 //! Now, let's look at Kotlin:
62 //!
63 //!   <https://github.com/JetBrains/kotlin/blob/a288b8b00e4754a1872b164999c6d3f3b8c8994a/idea/idea-frontend-fir/idea-fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/FirModuleResolveStateImpl.kt#L93-L125>
64 //!
65 //! This function starts with a syntax node (`KtExpression` is syntax, like all
66 //! `Kt` nodes), and returns a def. It uses
67 //! `getNonLocalContainingOrThisDeclaration` to get syntactic container for a
68 //! current node. Then, `findSourceNonLocalFirDeclaration` gets `Fir` for this
69 //! parent. Finally, `findElementIn` function traverses `Fir` children to find
70 //! one with the same source we originally started with.
71 //!
72 //! One question is left though -- where does the recursion stops? This happens
73 //! when we get to the file syntax node, which doesn't have a syntactic parent.
74 //! In that case, we loop through all the crates that might contain this file
75 //! and look for a module whose source is the given file.
76 //!
77 //! Note that the logic in this module is somewhat fundamentally imprecise --
78 //! due to conditional compilation and `#[path]` attributes, there's no
79 //! injective mapping from syntax nodes to defs. This is not an edge case --
80 //! more or less every item in a `lib.rs` is a part of two distinct crates: a
81 //! library with `--cfg test` and a library without.
82 //!
83 //! At the moment, we don't really handle this well and return the first answer
84 //! that works. Ideally, we should first let the caller to pick a specific
85 //! active crate for a given position, and then provide an API to resolve all
86 //! syntax nodes against this specific crate.
87
88 use base_db::FileId;
89 use hir_def::{
90     child_by_source::ChildBySource,
91     dyn_map::DynMap,
92     expr::{LabelId, PatId},
93     keys::{self, Key},
94     AdtId, ConstId, ConstParamId, DefWithBodyId, EnumId, EnumVariantId, FieldId, FunctionId,
95     GenericDefId, GenericParamId, ImplId, LifetimeParamId, ModuleId, StaticId, StructId, TraitId,
96     TypeAliasId, TypeParamId, UnionId, VariantId,
97 };
98 use hir_expand::{name::AsName, AstId, HirFileId, MacroCallId, MacroDefId, MacroDefKind};
99 use rustc_hash::FxHashMap;
100 use smallvec::SmallVec;
101 use stdx::impl_from;
102 use syntax::{
103     ast::{self, HasName},
104     match_ast, AstNode, SyntaxNode,
105 };
106
107 use crate::{db::HirDatabase, InFile};
108
109 pub(super) type SourceToDefCache = FxHashMap<(ChildContainer, HirFileId), DynMap>;
110
111 pub(super) struct SourceToDefCtx<'a, 'b> {
112     pub(super) db: &'b dyn HirDatabase,
113     pub(super) cache: &'a mut SourceToDefCache,
114 }
115
116 impl SourceToDefCtx<'_, '_> {
117     pub(super) fn file_to_def(&mut self, file: FileId) -> SmallVec<[ModuleId; 1]> {
118         let _p = profile::span("SourceBinder::to_module_def");
119         let mut mods = SmallVec::new();
120         for &crate_id in self.db.relevant_crates(file).iter() {
121             // FIXME: inner items
122             let crate_def_map = self.db.crate_def_map(crate_id);
123             mods.extend(
124                 crate_def_map
125                     .modules_for_file(file)
126                     .map(|local_id| crate_def_map.module_id(local_id)),
127             )
128         }
129         mods
130     }
131
132     pub(super) fn module_to_def(&mut self, src: InFile<ast::Module>) -> Option<ModuleId> {
133         let _p = profile::span("module_to_def");
134         let parent_declaration =
135             src.syntax().ancestors_with_macros_skip_attr_item(self.db.upcast()).skip(1).find_map(
136                 |it| {
137                     let m = ast::Module::cast(it.value.clone())?;
138                     Some(it.with_value(m))
139                 },
140             );
141
142         let parent_module = match parent_declaration {
143             Some(parent_declaration) => self.module_to_def(parent_declaration),
144             None => {
145                 let file_id = src.file_id.original_file(self.db.upcast());
146                 self.file_to_def(file_id).get(0).copied()
147             }
148         }?;
149
150         let child_name = src.value.name()?.as_name();
151         let def_map = parent_module.def_map(self.db.upcast());
152         let child_id = *def_map[parent_module.local_id].children.get(&child_name)?;
153         Some(def_map.module_id(child_id))
154     }
155
156     pub(super) fn source_file_to_def(&mut self, src: InFile<ast::SourceFile>) -> Option<ModuleId> {
157         let _p = profile::span("source_file_to_def");
158         let file_id = src.file_id.original_file(self.db.upcast());
159         self.file_to_def(file_id).get(0).copied()
160     }
161
162     pub(super) fn trait_to_def(&mut self, src: InFile<ast::Trait>) -> Option<TraitId> {
163         self.to_def(src, keys::TRAIT)
164     }
165     pub(super) fn impl_to_def(&mut self, src: InFile<ast::Impl>) -> Option<ImplId> {
166         self.to_def(src, keys::IMPL)
167     }
168     pub(super) fn fn_to_def(&mut self, src: InFile<ast::Fn>) -> Option<FunctionId> {
169         self.to_def(src, keys::FUNCTION)
170     }
171     pub(super) fn struct_to_def(&mut self, src: InFile<ast::Struct>) -> Option<StructId> {
172         self.to_def(src, keys::STRUCT)
173     }
174     pub(super) fn enum_to_def(&mut self, src: InFile<ast::Enum>) -> Option<EnumId> {
175         self.to_def(src, keys::ENUM)
176     }
177     pub(super) fn union_to_def(&mut self, src: InFile<ast::Union>) -> Option<UnionId> {
178         self.to_def(src, keys::UNION)
179     }
180     pub(super) fn static_to_def(&mut self, src: InFile<ast::Static>) -> Option<StaticId> {
181         self.to_def(src, keys::STATIC)
182     }
183     pub(super) fn const_to_def(&mut self, src: InFile<ast::Const>) -> Option<ConstId> {
184         self.to_def(src, keys::CONST)
185     }
186     pub(super) fn type_alias_to_def(&mut self, src: InFile<ast::TypeAlias>) -> Option<TypeAliasId> {
187         self.to_def(src, keys::TYPE_ALIAS)
188     }
189     pub(super) fn record_field_to_def(&mut self, src: InFile<ast::RecordField>) -> Option<FieldId> {
190         self.to_def(src, keys::RECORD_FIELD)
191     }
192     pub(super) fn tuple_field_to_def(&mut self, src: InFile<ast::TupleField>) -> Option<FieldId> {
193         self.to_def(src, keys::TUPLE_FIELD)
194     }
195     pub(super) fn enum_variant_to_def(
196         &mut self,
197         src: InFile<ast::Variant>,
198     ) -> Option<EnumVariantId> {
199         self.to_def(src, keys::VARIANT)
200     }
201     pub(super) fn adt_to_def(
202         &mut self,
203         InFile { file_id, value }: InFile<ast::Adt>,
204     ) -> Option<AdtId> {
205         match value {
206             ast::Adt::Enum(it) => self.enum_to_def(InFile::new(file_id, it)).map(AdtId::EnumId),
207             ast::Adt::Struct(it) => {
208                 self.struct_to_def(InFile::new(file_id, it)).map(AdtId::StructId)
209             }
210             ast::Adt::Union(it) => self.union_to_def(InFile::new(file_id, it)).map(AdtId::UnionId),
211         }
212     }
213     pub(super) fn bind_pat_to_def(
214         &mut self,
215         src: InFile<ast::IdentPat>,
216     ) -> Option<(DefWithBodyId, PatId)> {
217         let container = self.find_pat_or_label_container(src.syntax())?;
218         let (_body, source_map) = self.db.body_with_source_map(container);
219         let src = src.map(ast::Pat::from);
220         let pat_id = source_map.node_pat(src.as_ref())?;
221         Some((container, pat_id))
222     }
223     pub(super) fn self_param_to_def(
224         &mut self,
225         src: InFile<ast::SelfParam>,
226     ) -> Option<(DefWithBodyId, PatId)> {
227         let container = self.find_pat_or_label_container(src.syntax())?;
228         let (_body, source_map) = self.db.body_with_source_map(container);
229         let pat_id = source_map.node_self_param(src.as_ref())?;
230         Some((container, pat_id))
231     }
232     pub(super) fn label_to_def(
233         &mut self,
234         src: InFile<ast::Label>,
235     ) -> Option<(DefWithBodyId, LabelId)> {
236         let container = self.find_pat_or_label_container(src.syntax())?;
237         let (_body, source_map) = self.db.body_with_source_map(container);
238         let label_id = source_map.node_label(src.as_ref())?;
239         Some((container, label_id))
240     }
241
242     pub(super) fn item_to_macro_call(&mut self, src: InFile<ast::Item>) -> Option<MacroCallId> {
243         let map = self.dyn_map(src.as_ref())?;
244         map[keys::ATTR_MACRO].get(&src).copied()
245     }
246
247     pub(super) fn attr_to_derive_macro_call(
248         &mut self,
249         item: InFile<&ast::Item>,
250         src: InFile<ast::Attr>,
251     ) -> Option<&[Option<MacroCallId>]> {
252         let map = self.dyn_map(item)?;
253         map[keys::DERIVE_MACRO].get(&src).map(AsRef::as_ref)
254     }
255
256     fn to_def<Ast: AstNode + 'static, ID: Copy + 'static>(
257         &mut self,
258         src: InFile<Ast>,
259         key: Key<Ast, ID>,
260     ) -> Option<ID> {
261         self.dyn_map(src.as_ref())?[key].get(&src).copied()
262     }
263
264     fn dyn_map<Ast: AstNode + 'static>(&mut self, src: InFile<&Ast>) -> Option<&DynMap> {
265         let container = self.find_container(src.map(|it| it.syntax()))?;
266         Some(self.cache_for(container, src.file_id))
267     }
268
269     fn cache_for(&mut self, container: ChildContainer, file_id: HirFileId) -> &DynMap {
270         let db = self.db;
271         self.cache
272             .entry((container, file_id))
273             .or_insert_with(|| container.child_by_source(db, file_id))
274     }
275
276     pub(super) fn type_param_to_def(&mut self, src: InFile<ast::TypeParam>) -> Option<TypeParamId> {
277         let container: ChildContainer = self.find_generic_param_container(src.syntax())?.into();
278         let dyn_map = self.cache_for(container, src.file_id);
279         dyn_map[keys::TYPE_PARAM].get(&src).copied()
280     }
281
282     pub(super) fn lifetime_param_to_def(
283         &mut self,
284         src: InFile<ast::LifetimeParam>,
285     ) -> Option<LifetimeParamId> {
286         let container: ChildContainer = self.find_generic_param_container(src.syntax())?.into();
287         let dyn_map = self.cache_for(container, src.file_id);
288         dyn_map[keys::LIFETIME_PARAM].get(&src).copied()
289     }
290
291     pub(super) fn const_param_to_def(
292         &mut self,
293         src: InFile<ast::ConstParam>,
294     ) -> Option<ConstParamId> {
295         let container: ChildContainer = self.find_generic_param_container(src.syntax())?.into();
296         let dyn_map = self.cache_for(container, src.file_id);
297         dyn_map[keys::CONST_PARAM].get(&src).copied()
298     }
299
300     pub(super) fn generic_param_to_def(
301         &mut self,
302         InFile { file_id, value }: InFile<ast::GenericParam>,
303     ) -> Option<GenericParamId> {
304         match value {
305             ast::GenericParam::ConstParam(it) => {
306                 self.const_param_to_def(InFile::new(file_id, it)).map(GenericParamId::ConstParamId)
307             }
308             ast::GenericParam::LifetimeParam(it) => self
309                 .lifetime_param_to_def(InFile::new(file_id, it))
310                 .map(GenericParamId::LifetimeParamId),
311             ast::GenericParam::TypeParam(it) => {
312                 self.type_param_to_def(InFile::new(file_id, it)).map(GenericParamId::TypeParamId)
313             }
314         }
315     }
316
317     pub(super) fn macro_to_def(&mut self, src: InFile<ast::Macro>) -> Option<MacroDefId> {
318         let makro = self.dyn_map(src.as_ref()).and_then(|it| it[keys::MACRO].get(&src).copied());
319         if let res @ Some(_) = makro {
320             return res;
321         }
322
323         // Not all macros are recorded in the dyn map, only the ones behaving like items, so fall back
324         // for the non-item like definitions.
325         let file_ast_id = self.db.ast_id_map(src.file_id).ast_id(&src.value);
326         let ast_id = AstId::new(src.file_id, file_ast_id.upcast());
327         let kind = MacroDefKind::Declarative(ast_id);
328         let file_id = src.file_id.original_file(self.db.upcast());
329         let krate = self.file_to_def(file_id).get(0).copied()?.krate();
330         Some(MacroDefId { krate, kind, local_inner: false })
331     }
332
333     pub(super) fn find_container(&mut self, src: InFile<&SyntaxNode>) -> Option<ChildContainer> {
334         for container in src.ancestors_with_macros_skip_attr_item(self.db.upcast()).skip(1) {
335             if let Some(res) = self.container_to_def(container) {
336                 return Some(res);
337             }
338         }
339
340         let def = self.file_to_def(src.file_id.original_file(self.db.upcast())).get(0).copied()?;
341         Some(def.into())
342     }
343
344     fn container_to_def(&mut self, container: InFile<SyntaxNode>) -> Option<ChildContainer> {
345         let cont = match_ast! {
346             match (container.value) {
347                 ast::Module(it) => {
348                     let def = self.module_to_def(container.with_value(it))?;
349                     def.into()
350                 },
351                 ast::Trait(it) => {
352                     let def = self.trait_to_def(container.with_value(it))?;
353                     def.into()
354                 },
355                 ast::Impl(it) => {
356                     let def = self.impl_to_def(container.with_value(it))?;
357                     def.into()
358                 },
359                 ast::Fn(it) => {
360                     let def = self.fn_to_def(container.with_value(it))?;
361                     DefWithBodyId::from(def).into()
362                 },
363                 ast::Struct(it) => {
364                     let def = self.struct_to_def(container.with_value(it))?;
365                     VariantId::from(def).into()
366                 },
367                 ast::Enum(it) => {
368                     let def = self.enum_to_def(container.with_value(it))?;
369                     def.into()
370                 },
371                 ast::Union(it) => {
372                     let def = self.union_to_def(container.with_value(it))?;
373                     VariantId::from(def).into()
374                 },
375                 ast::Static(it) => {
376                     let def = self.static_to_def(container.with_value(it))?;
377                     DefWithBodyId::from(def).into()
378                 },
379                 ast::Const(it) => {
380                     let def = self.const_to_def(container.with_value(it))?;
381                     DefWithBodyId::from(def).into()
382                 },
383                 ast::TypeAlias(it) => {
384                     let def = self.type_alias_to_def(container.with_value(it))?;
385                     def.into()
386                 },
387                 ast::Variant(it) => {
388                     let def = self.enum_variant_to_def(container.with_value(it))?;
389                     VariantId::from(def).into()
390                 },
391                 _ => return None,
392             }
393         };
394         Some(cont)
395     }
396
397     fn find_generic_param_container(&mut self, src: InFile<&SyntaxNode>) -> Option<GenericDefId> {
398         for container in src.ancestors_with_macros_skip_attr_item(self.db.upcast()).skip(1) {
399             let res: GenericDefId = match_ast! {
400                 match (container.value) {
401                     ast::Fn(it) => self.fn_to_def(container.with_value(it))?.into(),
402                     ast::Struct(it) => self.struct_to_def(container.with_value(it))?.into(),
403                     ast::Enum(it) => self.enum_to_def(container.with_value(it))?.into(),
404                     ast::Trait(it) => self.trait_to_def(container.with_value(it))?.into(),
405                     ast::TypeAlias(it) => self.type_alias_to_def(container.with_value(it))?.into(),
406                     ast::Impl(it) => self.impl_to_def(container.with_value(it))?.into(),
407                     _ => continue,
408                 }
409             };
410             return Some(res);
411         }
412         None
413     }
414
415     fn find_pat_or_label_container(&mut self, src: InFile<&SyntaxNode>) -> Option<DefWithBodyId> {
416         for container in src.ancestors_with_macros_skip_attr_item(self.db.upcast()).skip(1) {
417             let res: DefWithBodyId = match_ast! {
418                 match (container.value) {
419                     ast::Const(it) => self.const_to_def(container.with_value(it))?.into(),
420                     ast::Static(it) => self.static_to_def(container.with_value(it))?.into(),
421                     ast::Fn(it) => self.fn_to_def(container.with_value(it))?.into(),
422                     _ => continue,
423                 }
424             };
425             return Some(res);
426         }
427         None
428     }
429 }
430
431 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
432 pub(crate) enum ChildContainer {
433     DefWithBodyId(DefWithBodyId),
434     ModuleId(ModuleId),
435     TraitId(TraitId),
436     ImplId(ImplId),
437     EnumId(EnumId),
438     VariantId(VariantId),
439     TypeAliasId(TypeAliasId),
440     /// XXX: this might be the same def as, for example an `EnumId`. However,
441     /// here the children are generic parameters, and not, eg enum variants.
442     GenericDefId(GenericDefId),
443 }
444 impl_from! {
445     DefWithBodyId,
446     ModuleId,
447     TraitId,
448     ImplId,
449     EnumId,
450     VariantId,
451     TypeAliasId,
452     GenericDefId
453     for ChildContainer
454 }
455
456 impl ChildContainer {
457     fn child_by_source(self, db: &dyn HirDatabase, file_id: HirFileId) -> DynMap {
458         let db = db.upcast();
459         match self {
460             ChildContainer::DefWithBodyId(it) => it.child_by_source(db, file_id),
461             ChildContainer::ModuleId(it) => it.child_by_source(db, file_id),
462             ChildContainer::TraitId(it) => it.child_by_source(db, file_id),
463             ChildContainer::ImplId(it) => it.child_by_source(db, file_id),
464             ChildContainer::EnumId(it) => it.child_by_source(db, file_id),
465             ChildContainer::VariantId(it) => it.child_by_source(db, file_id),
466             ChildContainer::TypeAliasId(_) => DynMap::default(),
467             ChildContainer::GenericDefId(it) => it.child_by_source(db, file_id),
468         }
469     }
470 }