aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
Diffstat (limited to 'crates')
-rw-r--r--crates/ra_hir/src/code_model.rs1
-rw-r--r--crates/ra_hir/src/from_id.rs12
-rw-r--r--crates/ra_hir/src/lib.rs1
-rw-r--r--crates/ra_hir/src/semantics.rs101
-rw-r--r--crates/ra_hir/src/semantics/source_to_def.rs271
-rw-r--r--crates/ra_hir/src/source_binder.rs284
6 files changed, 321 insertions, 349 deletions
diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs
index efc3502d0..a9615a3b7 100644
--- a/crates/ra_hir/src/code_model.rs
+++ b/crates/ra_hir/src/code_model.rs
@@ -778,6 +778,7 @@ impl GenericDef {
778 778
779#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] 779#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
780pub struct Local { 780pub struct Local {
781 // TODO: ID,
781 pub(crate) parent: DefWithBody, 782 pub(crate) parent: DefWithBody,
782 pub(crate) pat_id: PatId, 783 pub(crate) pat_id: PatId,
783} 784}
diff --git a/crates/ra_hir/src/from_id.rs b/crates/ra_hir/src/from_id.rs
index 3aa7c4870..88540fbf2 100644
--- a/crates/ra_hir/src/from_id.rs
+++ b/crates/ra_hir/src/from_id.rs
@@ -4,12 +4,12 @@
4//! are splitting the hir. 4//! are splitting the hir.
5 5
6use hir_def::{ 6use hir_def::{
7 AdtId, AssocItemId, AttrDefId, DefWithBodyId, EnumVariantId, GenericDefId, ModuleDefId, 7 expr::PatId, AdtId, AssocItemId, AttrDefId, DefWithBodyId, EnumVariantId, GenericDefId,
8 StructFieldId, VariantId, 8 ModuleDefId, StructFieldId, VariantId,
9}; 9};
10 10
11use crate::{ 11use crate::{
12 Adt, AssocItem, AttrDef, DefWithBody, EnumVariant, GenericDef, ModuleDef, StructField, 12 Adt, AssocItem, AttrDef, DefWithBody, EnumVariant, GenericDef, Local, ModuleDef, StructField,
13 VariantDef, 13 VariantDef,
14}; 14};
15 15
@@ -222,3 +222,9 @@ impl From<AssocItem> for GenericDefId {
222 } 222 }
223 } 223 }
224} 224}
225
226impl From<(DefWithBodyId, PatId)> for Local {
227 fn from((parent, pat_id): (DefWithBodyId, PatId)) -> Self {
228 Local { parent: parent.into(), pat_id }
229 }
230}
diff --git a/crates/ra_hir/src/lib.rs b/crates/ra_hir/src/lib.rs
index 3aa964fb6..cefbd80e6 100644
--- a/crates/ra_hir/src/lib.rs
+++ b/crates/ra_hir/src/lib.rs
@@ -29,7 +29,6 @@ macro_rules! impl_froms {
29mod semantics; 29mod semantics;
30pub mod db; 30pub mod db;
31mod source_analyzer; 31mod source_analyzer;
32mod source_binder;
33 32
34pub mod diagnostics; 33pub mod diagnostics;
35 34
diff --git a/crates/ra_hir/src/semantics.rs b/crates/ra_hir/src/semantics.rs
index 4a9cb7b3e..60392947e 100644
--- a/crates/ra_hir/src/semantics.rs
+++ b/crates/ra_hir/src/semantics.rs
@@ -1,32 +1,33 @@
1//! See `Semantics`. 1//! See `Semantics`.
2 2
3mod source_to_def;
4
3use std::{cell::RefCell, fmt, iter::successors}; 5use std::{cell::RefCell, fmt, iter::successors};
4 6
5use hir_def::{ 7use hir_def::{
6 resolver::{self, HasResolver, Resolver}, 8 resolver::{self, HasResolver, Resolver},
7 DefWithBodyId, TraitId, 9 TraitId,
8}; 10};
11use hir_expand::ExpansionInfo;
9use ra_db::{FileId, FileRange}; 12use ra_db::{FileId, FileRange};
13use ra_prof::profile;
10use ra_syntax::{ 14use ra_syntax::{
11 algo::skip_trivia_token, ast, match_ast, AstNode, Direction, SyntaxNode, SyntaxToken, 15 algo::skip_trivia_token, ast, AstNode, Direction, SyntaxNode, SyntaxToken, TextRange, TextUnit,
12 TextRange, TextUnit,
13}; 16};
14use rustc_hash::{FxHashMap, FxHashSet}; 17use rustc_hash::{FxHashMap, FxHashSet};
15 18
16use crate::{ 19use crate::{
17 db::HirDatabase, 20 db::HirDatabase,
21 semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx},
18 source_analyzer::{resolve_hir_path, ReferenceDescriptor, SourceAnalyzer}, 22 source_analyzer::{resolve_hir_path, ReferenceDescriptor, SourceAnalyzer},
19 source_binder::{ChildContainer, SourceBinder},
20 Function, HirFileId, InFile, Local, MacroDef, Module, ModuleDef, Name, Origin, Path, 23 Function, HirFileId, InFile, Local, MacroDef, Module, ModuleDef, Name, Origin, Path,
21 PathResolution, ScopeDef, StructField, Trait, Type, TypeParam, VariantDef, 24 PathResolution, ScopeDef, StructField, Trait, Type, TypeParam, VariantDef,
22}; 25};
23use hir_expand::ExpansionInfo;
24use ra_prof::profile;
25 26
26/// Primary API to get semantic information, like types, from syntax trees. 27/// Primary API to get semantic information, like types, from syntax trees.
27pub struct Semantics<'db, DB> { 28pub struct Semantics<'db, DB> {
28 pub db: &'db DB, 29 pub db: &'db DB,
29 sb: RefCell<SourceBinder>, 30 s2d_cache: RefCell<SourceToDefCache>,
30 cache: RefCell<FxHashMap<SyntaxNode, HirFileId>>, 31 cache: RefCell<FxHashMap<SyntaxNode, HirFileId>>,
31} 32}
32 33
@@ -38,8 +39,7 @@ impl<DB> fmt::Debug for Semantics<'_, DB> {
38 39
39impl<'db, DB: HirDatabase> Semantics<'db, DB> { 40impl<'db, DB: HirDatabase> Semantics<'db, DB> {
40 pub fn new(db: &DB) -> Semantics<DB> { 41 pub fn new(db: &DB) -> Semantics<DB> {
41 let sb = RefCell::new(SourceBinder::new()); 42 Semantics { db, s2d_cache: Default::default(), cache: Default::default() }
42 Semantics { db, sb, cache: RefCell::default() }
43 } 43 }
44 44
45 pub fn parse(&self, file_id: FileId) -> ast::SourceFile { 45 pub fn parse(&self, file_id: FileId) -> ast::SourceFile {
@@ -136,13 +136,19 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
136 // FIXME: use this instead? 136 // FIXME: use this instead?
137 // pub fn resolve_name_ref(&self, name_ref: &ast::NameRef) -> Option<???>; 137 // pub fn resolve_name_ref(&self, name_ref: &ast::NameRef) -> Option<???>;
138 138
139 pub fn to_def<T: ToDef + Clone>(&self, src: &T) -> Option<T::Def> { 139 pub fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> {
140 let src = self.find_file(src.syntax().clone()).with_value(src).cloned();
140 T::to_def(self, src) 141 T::to_def(self, src)
141 } 142 }
142 143
144 fn with_ctx<F: FnOnce(&mut SourceToDefCtx<&DB>) -> T, T>(&self, f: F) -> T {
145 let mut cache = self.s2d_cache.borrow_mut();
146 let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache };
147 f(&mut ctx)
148 }
149
143 pub fn to_module_def(&self, file: FileId) -> Option<Module> { 150 pub fn to_module_def(&self, file: FileId) -> Option<Module> {
144 let mut sb = self.sb.borrow_mut(); 151 self.with_ctx(|ctx| ctx.file_to_def(file)).map(Module::from)
145 sb.to_module_def(self.db, file)
146 } 152 }
147 153
148 pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db, DB> { 154 pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db, DB> {
@@ -176,7 +182,7 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
176 fn analyze2(&self, src: InFile<&SyntaxNode>, offset: Option<TextUnit>) -> SourceAnalyzer { 182 fn analyze2(&self, src: InFile<&SyntaxNode>, offset: Option<TextUnit>) -> SourceAnalyzer {
177 let _p = profile("Semantics::analyze2"); 183 let _p = profile("Semantics::analyze2");
178 184
179 let container = match self.sb.borrow_mut().find_container(self.db, src) { 185 let container = match self.with_ctx(|ctx| ctx.find_container(src)) {
180 Some(it) => it, 186 Some(it) => it,
181 None => return SourceAnalyzer::new_for_resolver(Resolver::default(), src), 187 None => return SourceAnalyzer::new_for_resolver(Resolver::default(), src),
182 }; 188 };
@@ -233,68 +239,41 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
233 } 239 }
234} 240}
235 241
236pub trait ToDef: Sized + AstNode + 'static { 242pub trait ToDef: AstNode + Clone {
237 type Def; 243 type Def;
238 fn to_def<DB: HirDatabase>(sema: &Semantics<DB>, src: &Self) -> Option<Self::Def>; 244
245 fn to_def<DB: HirDatabase>(sema: &Semantics<DB>, src: InFile<Self>) -> Option<Self::Def>;
239} 246}
240 247
241macro_rules! to_def_impls { 248macro_rules! to_def_impls {
242 ($(($def:path, $ast:path)),* ,) => {$( 249 ($(($def:path, $ast:path, $meth:ident)),* ,) => {$(
243 impl ToDef for $ast { 250 impl ToDef for $ast {
244 type Def = $def; 251 type Def = $def;
245 fn to_def<DB: HirDatabase>(sema: &Semantics<DB>, src: &Self) 252 fn to_def<DB: HirDatabase>(sema: &Semantics<DB>, src: InFile<Self>) -> Option<Self::Def> {
246 -> Option<Self::Def> 253 sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from)
247 {
248 let src = sema.find_file(src.syntax().clone()).with_value(src);
249 sema.sb.borrow_mut().to_id(sema.db, src.cloned()).map(Into::into)
250 } 254 }
251 } 255 }
252 )*} 256 )*}
253} 257}
254 258
255to_def_impls![ 259to_def_impls![
256 (crate::Module, ast::Module), 260 (crate::Module, ast::Module, module_to_def),
257 (crate::Struct, ast::StructDef), 261 (crate::Struct, ast::StructDef, struct_to_def),
258 (crate::Enum, ast::EnumDef), 262 (crate::Enum, ast::EnumDef, enum_to_def),
259 (crate::Union, ast::UnionDef), 263 (crate::Union, ast::UnionDef, union_to_def),
260 (crate::Trait, ast::TraitDef), 264 (crate::Trait, ast::TraitDef, trait_to_def),
261 (crate::ImplBlock, ast::ImplBlock), 265 (crate::ImplBlock, ast::ImplBlock, impl_to_def),
262 (crate::TypeAlias, ast::TypeAliasDef), 266 (crate::TypeAlias, ast::TypeAliasDef, type_alias_to_def),
263 (crate::Const, ast::ConstDef), 267 (crate::Const, ast::ConstDef, const_to_def),
264 (crate::Static, ast::StaticDef), 268 (crate::Static, ast::StaticDef, static_to_def),
265 (crate::Function, ast::FnDef), 269 (crate::Function, ast::FnDef, fn_to_def),
266 (crate::StructField, ast::RecordFieldDef), 270 (crate::StructField, ast::RecordFieldDef, record_field_to_def),
267 (crate::EnumVariant, ast::EnumVariant), 271 (crate::EnumVariant, ast::EnumVariant, enum_variant_to_def),
268 (crate::TypeParam, ast::TypeParam), 272 (crate::TypeParam, ast::TypeParam, type_param_to_def),
269 (crate::MacroDef, ast::MacroCall), // this one is dubious, not all calls are macros 273 (crate::MacroDef, ast::MacroCall, macro_call_to_def), // this one is dubious, not all calls are macros
274 (crate::Local, ast::BindPat, bind_pat_to_def),
270]; 275];
271 276
272impl ToDef for ast::BindPat {
273 type Def = Local;
274
275 fn to_def<DB: HirDatabase>(sema: &Semantics<DB>, src: &Self) -> Option<Local> {
276 let src = sema.find_file(src.syntax().clone()).with_value(src);
277 let file_id = src.file_id;
278 let mut sb = sema.sb.borrow_mut();
279 let db = sema.db;
280 let parent: DefWithBodyId = src.value.syntax().ancestors().find_map(|it| {
281 let res = match_ast! {
282 match it {
283 ast::ConstDef(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
284 ast::StaticDef(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
285 ast::FnDef(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
286 _ => return None,
287 }
288 };
289 Some(res)
290 })?;
291 let (_body, source_map) = db.body_with_source_map(parent);
292 let src = src.cloned().map(ast::Pat::from);
293 let pat_id = source_map.node_pat(src.as_ref())?;
294 Some(Local { parent: parent.into(), pat_id })
295 }
296}
297
298fn find_root(node: &SyntaxNode) -> SyntaxNode { 277fn find_root(node: &SyntaxNode) -> SyntaxNode {
299 node.ancestors().last().unwrap() 278 node.ancestors().last().unwrap()
300} 279}
diff --git a/crates/ra_hir/src/semantics/source_to_def.rs b/crates/ra_hir/src/semantics/source_to_def.rs
new file mode 100644
index 000000000..303610dc4
--- /dev/null
+++ b/crates/ra_hir/src/semantics/source_to_def.rs
@@ -0,0 +1,271 @@
1//! Maps *syntax* of various definitions to their semantic ids.
2
3use hir_def::{
4 child_by_source::ChildBySource,
5 dyn_map::DynMap,
6 expr::PatId,
7 keys::{self, Key},
8 ConstId, DefWithBodyId, EnumId, EnumVariantId, FunctionId, GenericDefId, ImplId, ModuleId,
9 StaticId, StructFieldId, StructId, TraitId, TypeAliasId, TypeParamId, UnionId, VariantId,
10};
11use hir_expand::{name::AsName, AstId, MacroDefKind};
12use ra_db::FileId;
13use ra_prof::profile;
14use ra_syntax::{
15 ast::{self, NameOwner},
16 match_ast, AstNode, SyntaxNode,
17};
18use rustc_hash::FxHashMap;
19
20use crate::{db::HirDatabase, InFile, MacroDefId};
21
22pub(super) type SourceToDefCache = FxHashMap<ChildContainer, DynMap>;
23
24pub(super) struct SourceToDefCtx<'a, DB> {
25 pub(super) db: DB,
26 pub(super) cache: &'a mut SourceToDefCache,
27}
28
29impl<DB: HirDatabase> SourceToDefCtx<'_, &'_ DB> {
30 pub(super) fn file_to_def(&mut self, file: FileId) -> Option<ModuleId> {
31 let _p = profile("SourceBinder::to_module_def");
32 let (krate, local_id) = self.db.relevant_crates(file).iter().find_map(|&crate_id| {
33 let crate_def_map = self.db.crate_def_map(crate_id);
34 let local_id = crate_def_map.modules_for_file(file).next()?;
35 Some((crate_id, local_id))
36 })?;
37 Some(ModuleId { krate, local_id })
38 }
39
40 pub(super) fn module_to_def(&mut self, src: InFile<ast::Module>) -> Option<ModuleId> {
41 let _p = profile("module_to_def");
42 let parent_declaration = src
43 .as_ref()
44 .map(|it| it.syntax())
45 .cloned()
46 .ancestors_with_macros(self.db)
47 .skip(1)
48 .find_map(|it| {
49 let m = ast::Module::cast(it.value.clone())?;
50 Some(it.with_value(m))
51 });
52
53 let parent_module = match parent_declaration {
54 Some(parent_declaration) => self.module_to_def(parent_declaration),
55 None => {
56 let file_id = src.file_id.original_file(self.db);
57 self.file_to_def(file_id)
58 }
59 }?;
60
61 let child_name = src.value.name()?.as_name();
62 let def_map = self.db.crate_def_map(parent_module.krate);
63 let child_id = *def_map[parent_module.local_id].children.get(&child_name)?;
64 Some(ModuleId { krate: parent_module.krate, local_id: child_id })
65 }
66
67 pub(super) fn trait_to_def(&mut self, src: InFile<ast::TraitDef>) -> Option<TraitId> {
68 self.to_def(src, keys::TRAIT)
69 }
70 pub(super) fn impl_to_def(&mut self, src: InFile<ast::ImplBlock>) -> Option<ImplId> {
71 self.to_def(src, keys::IMPL)
72 }
73 pub(super) fn fn_to_def(&mut self, src: InFile<ast::FnDef>) -> Option<FunctionId> {
74 self.to_def(src, keys::FUNCTION)
75 }
76 pub(super) fn struct_to_def(&mut self, src: InFile<ast::StructDef>) -> Option<StructId> {
77 self.to_def(src, keys::STRUCT)
78 }
79 pub(super) fn enum_to_def(&mut self, src: InFile<ast::EnumDef>) -> Option<EnumId> {
80 self.to_def(src, keys::ENUM)
81 }
82 pub(super) fn union_to_def(&mut self, src: InFile<ast::UnionDef>) -> Option<UnionId> {
83 self.to_def(src, keys::UNION)
84 }
85 pub(super) fn static_to_def(&mut self, src: InFile<ast::StaticDef>) -> Option<StaticId> {
86 self.to_def(src, keys::STATIC)
87 }
88 pub(super) fn const_to_def(&mut self, src: InFile<ast::ConstDef>) -> Option<ConstId> {
89 self.to_def(src, keys::CONST)
90 }
91 pub(super) fn type_alias_to_def(
92 &mut self,
93 src: InFile<ast::TypeAliasDef>,
94 ) -> Option<TypeAliasId> {
95 self.to_def(src, keys::TYPE_ALIAS)
96 }
97 //TODO: tuple field
98 pub(super) fn record_field_to_def(
99 &mut self,
100 src: InFile<ast::RecordFieldDef>,
101 ) -> Option<StructFieldId> {
102 self.to_def(src, keys::RECORD_FIELD)
103 }
104 pub(super) fn enum_variant_to_def(
105 &mut self,
106 src: InFile<ast::EnumVariant>,
107 ) -> Option<EnumVariantId> {
108 self.to_def(src, keys::ENUM_VARIANT)
109 }
110 pub(super) fn bind_pat_to_def(
111 &mut self,
112 src: InFile<ast::BindPat>,
113 ) -> Option<(DefWithBodyId, PatId)> {
114 let container = self.find_pat_container(src.as_ref().map(|it| it.syntax()))?;
115 let (_body, source_map) = self.db.body_with_source_map(container);
116 let src = src.map(ast::Pat::from);
117 let pat_id = source_map.node_pat(src.as_ref())?;
118 Some((container, pat_id))
119 }
120
121 fn to_def<Ast: AstNode + 'static, ID: Copy + 'static>(
122 &mut self,
123 src: InFile<Ast>,
124 key: Key<Ast, ID>,
125 ) -> Option<ID> {
126 let container = self.find_container(src.as_ref().map(|it| it.syntax()))?;
127 let db = self.db;
128 let dyn_map =
129 &*self.cache.entry(container).or_insert_with(|| container.child_by_source(db));
130 dyn_map[key].get(&src).copied()
131 }
132
133 pub(super) fn type_param_to_def(&mut self, src: InFile<ast::TypeParam>) -> Option<TypeParamId> {
134 let container: ChildContainer =
135 self.find_type_param_container(src.as_ref().map(|it| it.syntax()))?.into();
136 let db = self.db;
137 let dyn_map =
138 &*self.cache.entry(container).or_insert_with(|| container.child_by_source(db));
139 dyn_map[keys::TYPE_PARAM].get(&src).copied()
140 }
141
142 // FIXME: use DynMap as well?
143 pub(super) fn macro_call_to_def(&mut self, src: InFile<ast::MacroCall>) -> Option<MacroDefId> {
144 let kind = MacroDefKind::Declarative;
145 let file_id = src.file_id.original_file(self.db);
146 let krate = self.file_to_def(file_id)?.krate;
147 let file_ast_id = self.db.ast_id_map(src.file_id).ast_id(&src.value);
148 let ast_id = Some(AstId::new(src.file_id, file_ast_id));
149 Some(MacroDefId { krate: Some(krate), ast_id, kind })
150 }
151
152 pub(super) fn find_container(&mut self, src: InFile<&SyntaxNode>) -> Option<ChildContainer> {
153 for container in src.cloned().ancestors_with_macros(self.db).skip(1) {
154 let res: ChildContainer = match_ast! {
155 match (container.value) {
156 ast::Module(it) => {
157 let def = self.module_to_def(container.with_value(it))?;
158 def.into()
159 },
160 ast::TraitDef(it) => {
161 let def = self.trait_to_def(container.with_value(it))?;
162 def.into()
163 },
164 ast::ImplBlock(it) => {
165 let def = self.impl_to_def(container.with_value(it))?;
166 def.into()
167 },
168 ast::FnDef(it) => {
169 let def = self.fn_to_def(container.with_value(it))?;
170 DefWithBodyId::from(def).into()
171 },
172 ast::StructDef(it) => {
173 let def = self.struct_to_def(container.with_value(it))?;
174 VariantId::from(def).into()
175 },
176 ast::EnumDef(it) => {
177 let def = self.enum_to_def(container.with_value(it))?;
178 def.into()
179 },
180 ast::UnionDef(it) => {
181 let def = self.union_to_def(container.with_value(it))?;
182 VariantId::from(def).into()
183 },
184 ast::StaticDef(it) => {
185 let def = self.static_to_def(container.with_value(it))?;
186 DefWithBodyId::from(def).into()
187 },
188 ast::ConstDef(it) => {
189 let def = self.const_to_def(container.with_value(it))?;
190 DefWithBodyId::from(def).into()
191 },
192 _ => continue,
193 }
194 };
195 return Some(res);
196 }
197
198 let def = self.file_to_def(src.file_id.original_file(self.db))?;
199 Some(def.into())
200 }
201
202 fn find_type_param_container(&mut self, src: InFile<&SyntaxNode>) -> Option<GenericDefId> {
203 for container in src.cloned().ancestors_with_macros(self.db).skip(1) {
204 let res: GenericDefId = match_ast! {
205 match (container.value) {
206 ast::FnDef(it) => { self.fn_to_def(container.with_value(it))?.into() },
207 ast::StructDef(it) => { self.struct_to_def(container.with_value(it))?.into() },
208 ast::EnumDef(it) => { self.enum_to_def(container.with_value(it))?.into() },
209 ast::TraitDef(it) => { self.trait_to_def(container.with_value(it))?.into() },
210 ast::TypeAliasDef(it) => { self.type_alias_to_def(container.with_value(it))?.into() },
211 ast::ImplBlock(it) => { self.impl_to_def(container.with_value(it))?.into() },
212 _ => continue,
213 }
214 };
215 return Some(res);
216 }
217 None
218 }
219
220 fn find_pat_container(&mut self, src: InFile<&SyntaxNode>) -> Option<DefWithBodyId> {
221 for container in src.cloned().ancestors_with_macros(self.db).skip(1) {
222 let res: DefWithBodyId = match_ast! {
223 match (container.value) {
224 ast::ConstDef(it) => { self.const_to_def(container.with_value(it))?.into() },
225 ast::StaticDef(it) => { self.static_to_def(container.with_value(it))?.into() },
226 ast::FnDef(it) => { self.fn_to_def(container.with_value(it))?.into() },
227 _ => continue,
228 }
229 };
230 return Some(res);
231 }
232 None
233 }
234}
235
236#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
237pub(crate) enum ChildContainer {
238 DefWithBodyId(DefWithBodyId),
239 ModuleId(ModuleId),
240 TraitId(TraitId),
241 ImplId(ImplId),
242 EnumId(EnumId),
243 VariantId(VariantId),
244 /// XXX: this might be the same def as, for example an `EnumId`. However,
245 /// here the children generic parameters, and not, eg enum variants.
246 GenericDefId(GenericDefId),
247}
248impl_froms! {
249 ChildContainer:
250 DefWithBodyId,
251 ModuleId,
252 TraitId,
253 ImplId,
254 EnumId,
255 VariantId,
256 GenericDefId
257}
258
259impl ChildContainer {
260 fn child_by_source(self, db: &impl HirDatabase) -> DynMap {
261 match self {
262 ChildContainer::DefWithBodyId(it) => it.child_by_source(db),
263 ChildContainer::ModuleId(it) => it.child_by_source(db),
264 ChildContainer::TraitId(it) => it.child_by_source(db),
265 ChildContainer::ImplId(it) => it.child_by_source(db),
266 ChildContainer::EnumId(it) => it.child_by_source(db),
267 ChildContainer::VariantId(it) => it.child_by_source(db),
268 ChildContainer::GenericDefId(it) => it.child_by_source(db),
269 }
270 }
271}
diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs
deleted file mode 100644
index 439a4d5db..000000000
--- a/crates/ra_hir/src/source_binder.rs
+++ /dev/null
@@ -1,284 +0,0 @@
1//! `SourceBinder` is the main entry point for getting info about source code.
2//! It's main task is to map source syntax trees to hir-level IDs.
3
4use hir_def::{
5 child_by_source::ChildBySource,
6 dyn_map::DynMap,
7 keys::{self, Key},
8 ConstId, DefWithBodyId, EnumId, EnumVariantId, FunctionId, GenericDefId, ImplId, ModuleId,
9 StaticId, StructFieldId, StructId, TraitId, TypeAliasId, TypeParamId, UnionId, VariantId,
10};
11use hir_expand::{name::AsName, AstId, InFile, MacroDefId, MacroDefKind};
12use ra_db::FileId;
13use ra_prof::profile;
14use ra_syntax::{
15 ast::{self, NameOwner},
16 match_ast, AstNode, SyntaxNode,
17};
18use rustc_hash::FxHashMap;
19
20use crate::{db::HirDatabase, Module};
21
22pub(crate) struct SourceBinder {
23 child_by_source_cache: FxHashMap<ChildContainer, DynMap>,
24}
25
26impl SourceBinder {
27 pub(crate) fn new() -> SourceBinder {
28 SourceBinder { child_by_source_cache: FxHashMap::default() }
29 }
30
31 pub(crate) fn to_module_def(&mut self, db: &impl HirDatabase, file: FileId) -> Option<Module> {
32 let _p = profile("SourceBinder::to_module_def");
33 let (krate, local_id) = db.relevant_crates(file).iter().find_map(|&crate_id| {
34 let crate_def_map = 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(Module { id: ModuleId { krate, local_id } })
39 }
40
41 pub(crate) fn to_id<T: ToId>(
42 &mut self,
43 db: &impl HirDatabase,
44 src: InFile<T>,
45 ) -> Option<T::ID> {
46 T::to_id(db, self, src)
47 }
48
49 pub(crate) fn find_container(
50 &mut self,
51 db: &impl HirDatabase,
52 src: InFile<&SyntaxNode>,
53 ) -> Option<ChildContainer> {
54 for container in src.cloned().ancestors_with_macros(db).skip(1) {
55 let res: ChildContainer = match_ast! {
56 match (container.value) {
57 ast::TraitDef(it) => {
58 let def: TraitId = self.to_id(db, container.with_value(it))?;
59 def.into()
60 },
61 ast::ImplBlock(it) => {
62 let def: ImplId = self.to_id(db, container.with_value(it))?;
63 def.into()
64 },
65 ast::FnDef(it) => {
66 let def: FunctionId = self.to_id(db, container.with_value(it))?;
67 DefWithBodyId::from(def).into()
68 },
69 ast::StaticDef(it) => {
70 let def: StaticId = self.to_id(db, container.with_value(it))?;
71 DefWithBodyId::from(def).into()
72 },
73 ast::ConstDef(it) => {
74 let def: ConstId = self.to_id(db, container.with_value(it))?;
75 DefWithBodyId::from(def).into()
76 },
77 ast::EnumDef(it) => {
78 let def: EnumId = self.to_id(db, container.with_value(it))?;
79 def.into()
80 },
81 ast::StructDef(it) => {
82 let def: StructId = self.to_id(db, container.with_value(it))?;
83 VariantId::from(def).into()
84 },
85 ast::UnionDef(it) => {
86 let def: UnionId = self.to_id(db, container.with_value(it))?;
87 VariantId::from(def).into()
88 },
89 ast::Module(it) => {
90 let def: ModuleId = self.to_id(db, container.with_value(it))?;
91 def.into()
92 },
93 _ => { continue },
94 }
95 };
96 return Some(res);
97 }
98
99 let c = self.to_module_def(db, src.file_id.original_file(db))?;
100 Some(c.id.into())
101 }
102
103 fn child_by_source(&mut self, db: &impl HirDatabase, container: ChildContainer) -> &DynMap {
104 self.child_by_source_cache.entry(container).or_insert_with(|| container.child_by_source(db))
105 }
106}
107
108pub(crate) trait ToId: Sized {
109 type ID: Sized + Copy + 'static;
110 fn to_id<DB: HirDatabase>(
111 db: &DB,
112 sb: &mut SourceBinder,
113 src: InFile<Self>,
114 ) -> Option<Self::ID>;
115}
116
117#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
118pub(crate) enum ChildContainer {
119 DefWithBodyId(DefWithBodyId),
120 ModuleId(ModuleId),
121 TraitId(TraitId),
122 ImplId(ImplId),
123 EnumId(EnumId),
124 VariantId(VariantId),
125 /// XXX: this might be the same def as, for example an `EnumId`. However,
126 /// here the children generic parameters, and not, eg enum variants.
127 GenericDefId(GenericDefId),
128}
129impl_froms! {
130 ChildContainer:
131 DefWithBodyId,
132 ModuleId,
133 TraitId,
134 ImplId,
135 EnumId,
136 VariantId,
137 GenericDefId
138}
139
140impl ChildContainer {
141 fn child_by_source(self, db: &impl HirDatabase) -> DynMap {
142 match self {
143 ChildContainer::DefWithBodyId(it) => it.child_by_source(db),
144 ChildContainer::ModuleId(it) => it.child_by_source(db),
145 ChildContainer::TraitId(it) => it.child_by_source(db),
146 ChildContainer::ImplId(it) => it.child_by_source(db),
147 ChildContainer::EnumId(it) => it.child_by_source(db),
148 ChildContainer::VariantId(it) => it.child_by_source(db),
149 ChildContainer::GenericDefId(it) => it.child_by_source(db),
150 }
151 }
152}
153
154pub(crate) trait ToIdByKey: Sized + AstNode + 'static {
155 type ID: Sized + Copy + 'static;
156 const KEY: Key<Self, Self::ID>;
157}
158
159impl<T: ToIdByKey> ToId for T {
160 type ID = <T as ToIdByKey>::ID;
161 fn to_id<DB: HirDatabase>(
162 db: &DB,
163 sb: &mut SourceBinder,
164 src: InFile<Self>,
165 ) -> Option<Self::ID> {
166 let container = sb.find_container(db, src.as_ref().map(|it| it.syntax()))?;
167 let dyn_map =
168 &*sb.child_by_source_cache.entry(container).or_insert_with(|| match container {
169 ChildContainer::DefWithBodyId(it) => it.child_by_source(db),
170 ChildContainer::ModuleId(it) => it.child_by_source(db),
171 ChildContainer::TraitId(it) => it.child_by_source(db),
172 ChildContainer::ImplId(it) => it.child_by_source(db),
173 ChildContainer::EnumId(it) => it.child_by_source(db),
174 ChildContainer::VariantId(it) => it.child_by_source(db),
175 ChildContainer::GenericDefId(it) => it.child_by_source(db),
176 });
177 dyn_map[T::KEY].get(&src).copied()
178 }
179}
180
181macro_rules! to_id_key_impls {
182 ($(($id:ident, $ast:path, $key:path)),* ,) => {$(
183 impl ToIdByKey for $ast {
184 type ID = $id;
185 const KEY: Key<Self, Self::ID> = $key;
186 }
187 )*}
188}
189
190to_id_key_impls![
191 (StructId, ast::StructDef, keys::STRUCT),
192 (UnionId, ast::UnionDef, keys::UNION),
193 (EnumId, ast::EnumDef, keys::ENUM),
194 (TraitId, ast::TraitDef, keys::TRAIT),
195 (FunctionId, ast::FnDef, keys::FUNCTION),
196 (StaticId, ast::StaticDef, keys::STATIC),
197 (ConstId, ast::ConstDef, keys::CONST),
198 (TypeAliasId, ast::TypeAliasDef, keys::TYPE_ALIAS),
199 (ImplId, ast::ImplBlock, keys::IMPL),
200 (StructFieldId, ast::RecordFieldDef, keys::RECORD_FIELD),
201 (EnumVariantId, ast::EnumVariant, keys::ENUM_VARIANT),
202];
203
204// FIXME: use DynMap as well?
205impl ToId for ast::MacroCall {
206 type ID = MacroDefId;
207 fn to_id<DB: HirDatabase>(
208 db: &DB,
209 sb: &mut SourceBinder,
210 src: InFile<Self>,
211 ) -> Option<Self::ID> {
212 let kind = MacroDefKind::Declarative;
213
214 let krate = sb.to_module_def(db, src.file_id.original_file(db))?.id.krate;
215
216 let ast_id = Some(AstId::new(src.file_id, db.ast_id_map(src.file_id).ast_id(&src.value)));
217
218 Some(MacroDefId { krate: Some(krate), ast_id, kind })
219 }
220}
221
222impl ToId for ast::TypeParam {
223 type ID = TypeParamId;
224
225 fn to_id<DB: HirDatabase>(
226 db: &DB,
227 sb: &mut SourceBinder,
228 src: InFile<Self>,
229 ) -> Option<Self::ID> {
230 let file_id = src.file_id;
231 let parent: GenericDefId = src.value.syntax().ancestors().find_map(|it| {
232 let res = match_ast! {
233 match it {
234 ast::FnDef(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
235 ast::StructDef(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
236 ast::EnumDef(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
237 ast::TraitDef(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
238 ast::TypeAliasDef(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
239 ast::ImplBlock(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
240 _ => return None,
241 }
242 };
243 Some(res)
244 })?;
245 sb.child_by_source(db, parent.into())[keys::TYPE_PARAM].get(&src).copied()
246 }
247}
248
249impl ToId for ast::Module {
250 type ID = ModuleId;
251
252 fn to_id<DB: HirDatabase>(
253 db: &DB,
254 sb: &mut SourceBinder,
255 src: InFile<ast::Module>,
256 ) -> Option<ModuleId> {
257 {
258 let _p = profile("ast::Module::to_def");
259 let parent_declaration = src
260 .as_ref()
261 .map(|it| it.syntax())
262 .cloned()
263 .ancestors_with_macros(db)
264 .skip(1)
265 .find_map(|it| {
266 let m = ast::Module::cast(it.value.clone())?;
267 Some(it.with_value(m))
268 });
269
270 let parent_module = match parent_declaration {
271 Some(parent_declaration) => sb.to_id(db, parent_declaration)?,
272 None => {
273 let file_id = src.file_id.original_file(db);
274 sb.to_module_def(db, file_id)?.id
275 }
276 };
277
278 let child_name = src.value.name()?.as_name();
279 let def_map = db.crate_def_map(parent_module.krate);
280 let child_id = *def_map[parent_module.local_id].children.get(&child_name)?;
281 Some(ModuleId { krate: parent_module.krate, local_id: child_id })
282 }
283 }
284}