aboutsummaryrefslogtreecommitdiff
path: root/crates/ide_db/src
diff options
context:
space:
mode:
authorbors[bot] <26634292+bors[bot]@users.noreply.github.com>2021-01-16 17:52:29 +0000
committerGitHub <[email protected]>2021-01-16 17:52:29 +0000
commit9a349f280ff1c6d0b57df80aa3d6720474e4b00a (patch)
tree23bbb365f31438949358a576bc9467fa70fa874e /crates/ide_db/src
parent3782c78d7558633be5483a04aa1c098fe76100b9 (diff)
parent497fc232e7d90d8d39c7a13742dd85d758dc2f72 (diff)
Merge #7295
7295: Share import_assets and related entities r=matklad a=SomeoneToIgnore Part of https://github.com/rust-analyzer/rust-analyzer/pull/7293 Addresses https://github.com/rust-analyzer/rust-analyzer/pull/7293#issuecomment-761569558 Prepares `import_assets` and related to be used later for the trait fuzzy importing. Also moves fuzzy imports into a separate completion module and renames them, as suggested in https://github.com/rust-analyzer/rust-analyzer/pull/7293#discussion_r558896685 Co-authored-by: Kirill Bulatov <[email protected]>
Diffstat (limited to 'crates/ide_db/src')
-rw-r--r--crates/ide_db/src/helpers.rs1
-rw-r--r--crates/ide_db/src/helpers/import_assets.rs267
-rw-r--r--crates/ide_db/src/helpers/insert_use.rs6
-rw-r--r--crates/ide_db/src/imports_locator.rs6
4 files changed, 278 insertions, 2 deletions
diff --git a/crates/ide_db/src/helpers.rs b/crates/ide_db/src/helpers.rs
index c6763ae36..0dcc4dd29 100644
--- a/crates/ide_db/src/helpers.rs
+++ b/crates/ide_db/src/helpers.rs
@@ -1,5 +1,6 @@
1//! A module with ide helpers for high-level ide features. 1//! A module with ide helpers for high-level ide features.
2pub mod insert_use; 2pub mod insert_use;
3pub mod import_assets;
3 4
4use hir::{Crate, Enum, Module, ScopeDef, Semantics, Trait}; 5use hir::{Crate, Enum, Module, ScopeDef, Semantics, Trait};
5use syntax::ast::{self, make}; 6use syntax::ast::{self, make};
diff --git a/crates/ide_db/src/helpers/import_assets.rs b/crates/ide_db/src/helpers/import_assets.rs
new file mode 100644
index 000000000..edc3da318
--- /dev/null
+++ b/crates/ide_db/src/helpers/import_assets.rs
@@ -0,0 +1,267 @@
1//! Look up accessible paths for items.
2use either::Either;
3use hir::{AsAssocItem, AssocItemContainer, ModuleDef, Semantics};
4use rustc_hash::FxHashSet;
5use syntax::{ast, AstNode, SyntaxNode};
6
7use crate::{imports_locator, RootDatabase};
8
9use super::insert_use::InsertUseConfig;
10
11#[derive(Debug)]
12pub enum ImportCandidate {
13 // A path, qualified (`std::collections::HashMap`) or not (`HashMap`).
14 Path(PathImportCandidate),
15 /// A trait associated function (with no self parameter) or associated constant.
16 /// For 'test_mod::TestEnum::test_function', `ty` is the `test_mod::TestEnum` expression type
17 /// and `name` is the `test_function`
18 TraitAssocItem(TraitImportCandidate),
19 /// A trait method with self parameter.
20 /// For 'test_enum.test_method()', `ty` is the `test_enum` expression type
21 /// and `name` is the `test_method`
22 TraitMethod(TraitImportCandidate),
23}
24
25#[derive(Debug)]
26pub struct TraitImportCandidate {
27 pub ty: hir::Type,
28 pub name: ast::NameRef,
29}
30
31#[derive(Debug)]
32pub struct PathImportCandidate {
33 pub qualifier: Option<ast::Path>,
34 pub name: ast::NameRef,
35}
36
37#[derive(Debug)]
38pub struct ImportAssets {
39 import_candidate: ImportCandidate,
40 module_with_name_to_import: hir::Module,
41 syntax_under_caret: SyntaxNode,
42}
43
44impl ImportAssets {
45 pub fn for_method_call(
46 method_call: ast::MethodCallExpr,
47 sema: &Semantics<RootDatabase>,
48 ) -> Option<Self> {
49 let syntax_under_caret = method_call.syntax().to_owned();
50 let module_with_name_to_import = sema.scope(&syntax_under_caret).module()?;
51 Some(Self {
52 import_candidate: ImportCandidate::for_method_call(sema, &method_call)?,
53 module_with_name_to_import,
54 syntax_under_caret,
55 })
56 }
57
58 pub fn for_regular_path(
59 path_under_caret: ast::Path,
60 sema: &Semantics<RootDatabase>,
61 ) -> Option<Self> {
62 let syntax_under_caret = path_under_caret.syntax().to_owned();
63 if syntax_under_caret.ancestors().find_map(ast::Use::cast).is_some() {
64 return None;
65 }
66
67 let module_with_name_to_import = sema.scope(&syntax_under_caret).module()?;
68 Some(Self {
69 import_candidate: ImportCandidate::for_regular_path(sema, &path_under_caret)?,
70 module_with_name_to_import,
71 syntax_under_caret,
72 })
73 }
74
75 pub fn syntax_under_caret(&self) -> &SyntaxNode {
76 &self.syntax_under_caret
77 }
78
79 pub fn import_candidate(&self) -> &ImportCandidate {
80 &self.import_candidate
81 }
82
83 fn get_search_query(&self) -> &str {
84 match &self.import_candidate {
85 ImportCandidate::Path(candidate) => candidate.name.text(),
86 ImportCandidate::TraitAssocItem(candidate)
87 | ImportCandidate::TraitMethod(candidate) => candidate.name.text(),
88 }
89 }
90
91 pub fn search_for_imports(
92 &self,
93 sema: &Semantics<RootDatabase>,
94 config: &InsertUseConfig,
95 ) -> Vec<(hir::ModPath, hir::ItemInNs)> {
96 let _p = profile::span("import_assists::search_for_imports");
97 self.search_for(sema, Some(config.prefix_kind))
98 }
99
100 /// This may return non-absolute paths if a part of the returned path is already imported into scope.
101 #[allow(dead_code)]
102 pub fn search_for_relative_paths(
103 &self,
104 sema: &Semantics<RootDatabase>,
105 ) -> Vec<(hir::ModPath, hir::ItemInNs)> {
106 let _p = profile::span("import_assists::search_for_relative_paths");
107 self.search_for(sema, None)
108 }
109
110 fn search_for(
111 &self,
112 sema: &Semantics<RootDatabase>,
113 prefixed: Option<hir::PrefixKind>,
114 ) -> Vec<(hir::ModPath, hir::ItemInNs)> {
115 let db = sema.db;
116 let mut trait_candidates = FxHashSet::default();
117 let current_crate = self.module_with_name_to_import.krate();
118
119 let filter = |candidate: Either<hir::ModuleDef, hir::MacroDef>| {
120 trait_candidates.clear();
121 match &self.import_candidate {
122 ImportCandidate::TraitAssocItem(trait_candidate) => {
123 let located_assoc_item = match candidate {
124 Either::Left(ModuleDef::Function(located_function)) => {
125 located_function.as_assoc_item(db)
126 }
127 Either::Left(ModuleDef::Const(located_const)) => {
128 located_const.as_assoc_item(db)
129 }
130 _ => None,
131 }
132 .map(|assoc| assoc.container(db))
133 .and_then(Self::assoc_to_trait)?;
134
135 trait_candidates.insert(located_assoc_item.into());
136
137 trait_candidate
138 .ty
139 .iterate_path_candidates(
140 db,
141 current_crate,
142 &trait_candidates,
143 None,
144 |_, assoc| Self::assoc_to_trait(assoc.container(db)),
145 )
146 .map(ModuleDef::from)
147 .map(Either::Left)
148 }
149 ImportCandidate::TraitMethod(trait_candidate) => {
150 let located_assoc_item =
151 if let Either::Left(ModuleDef::Function(located_function)) = candidate {
152 located_function
153 .as_assoc_item(db)
154 .map(|assoc| assoc.container(db))
155 .and_then(Self::assoc_to_trait)
156 } else {
157 None
158 }?;
159
160 trait_candidates.insert(located_assoc_item.into());
161
162 trait_candidate
163 .ty
164 .iterate_method_candidates(
165 db,
166 current_crate,
167 &trait_candidates,
168 None,
169 |_, function| {
170 Self::assoc_to_trait(function.as_assoc_item(db)?.container(db))
171 },
172 )
173 .map(ModuleDef::from)
174 .map(Either::Left)
175 }
176 _ => Some(candidate),
177 }
178 };
179
180 let mut res = imports_locator::find_exact_imports(
181 sema,
182 current_crate,
183 self.get_search_query().to_string(),
184 )
185 .filter_map(filter)
186 .filter_map(|candidate| {
187 let item: hir::ItemInNs = candidate.either(Into::into, Into::into);
188 if let Some(prefix_kind) = prefixed {
189 self.module_with_name_to_import.find_use_path_prefixed(db, item, prefix_kind)
190 } else {
191 self.module_with_name_to_import.find_use_path(db, item)
192 }
193 .map(|path| (path, item))
194 })
195 .filter(|(use_path, _)| use_path.len() > 1)
196 .take(20)
197 .collect::<Vec<_>>();
198 res.sort_by_key(|(path, _)| path.clone());
199 res
200 }
201
202 fn assoc_to_trait(assoc: AssocItemContainer) -> Option<hir::Trait> {
203 if let AssocItemContainer::Trait(extracted_trait) = assoc {
204 Some(extracted_trait)
205 } else {
206 None
207 }
208 }
209}
210
211impl ImportCandidate {
212 fn for_method_call(
213 sema: &Semantics<RootDatabase>,
214 method_call: &ast::MethodCallExpr,
215 ) -> Option<Self> {
216 match sema.resolve_method_call(method_call) {
217 Some(_) => None,
218 None => Some(Self::TraitMethod(TraitImportCandidate {
219 ty: sema.type_of_expr(&method_call.receiver()?)?,
220 name: method_call.name_ref()?,
221 })),
222 }
223 }
224
225 fn for_regular_path(
226 sema: &Semantics<RootDatabase>,
227 path_under_caret: &ast::Path,
228 ) -> Option<Self> {
229 if sema.resolve_path(path_under_caret).is_some() {
230 return None;
231 }
232
233 let segment = path_under_caret.segment()?;
234 let candidate = if let Some(qualifier) = path_under_caret.qualifier() {
235 let qualifier_start = qualifier.syntax().descendants().find_map(ast::NameRef::cast)?;
236 let qualifier_start_path =
237 qualifier_start.syntax().ancestors().find_map(ast::Path::cast)?;
238 if let Some(qualifier_start_resolution) = sema.resolve_path(&qualifier_start_path) {
239 let qualifier_resolution = if qualifier_start_path == qualifier {
240 qualifier_start_resolution
241 } else {
242 sema.resolve_path(&qualifier)?
243 };
244 match qualifier_resolution {
245 hir::PathResolution::Def(hir::ModuleDef::Adt(assoc_item_path)) => {
246 ImportCandidate::TraitAssocItem(TraitImportCandidate {
247 ty: assoc_item_path.ty(sema.db),
248 name: segment.name_ref()?,
249 })
250 }
251 _ => return None,
252 }
253 } else {
254 ImportCandidate::Path(PathImportCandidate {
255 qualifier: Some(qualifier),
256 name: qualifier_start,
257 })
258 }
259 } else {
260 ImportCandidate::Path(PathImportCandidate {
261 qualifier: None,
262 name: segment.syntax().descendants().find_map(ast::NameRef::cast)?,
263 })
264 };
265 Some(candidate)
266 }
267}
diff --git a/crates/ide_db/src/helpers/insert_use.rs b/crates/ide_db/src/helpers/insert_use.rs
index d2f9f5d25..877d4f1c7 100644
--- a/crates/ide_db/src/helpers/insert_use.rs
+++ b/crates/ide_db/src/helpers/insert_use.rs
@@ -15,6 +15,12 @@ use syntax::{
15}; 15};
16use test_utils::mark; 16use test_utils::mark;
17 17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub struct InsertUseConfig {
20 pub merge: Option<MergeBehavior>,
21 pub prefix_kind: hir::PrefixKind,
22}
23
18#[derive(Debug, Clone)] 24#[derive(Debug, Clone)]
19pub enum ImportScope { 25pub enum ImportScope {
20 File(ast::SourceFile), 26 File(ast::SourceFile),
diff --git a/crates/ide_db/src/imports_locator.rs b/crates/ide_db/src/imports_locator.rs
index e9f23adf8..d111fba92 100644
--- a/crates/ide_db/src/imports_locator.rs
+++ b/crates/ide_db/src/imports_locator.rs
@@ -12,6 +12,8 @@ use crate::{
12use either::Either; 12use either::Either;
13use rustc_hash::FxHashSet; 13use rustc_hash::FxHashSet;
14 14
15const QUERY_SEARCH_LIMIT: usize = 40;
16
15pub fn find_exact_imports<'a>( 17pub fn find_exact_imports<'a>(
16 sema: &Semantics<'a, RootDatabase>, 18 sema: &Semantics<'a, RootDatabase>,
17 krate: Crate, 19 krate: Crate,
@@ -24,11 +26,11 @@ pub fn find_exact_imports<'a>(
24 { 26 {
25 let mut local_query = symbol_index::Query::new(name_to_import.clone()); 27 let mut local_query = symbol_index::Query::new(name_to_import.clone());
26 local_query.exact(); 28 local_query.exact();
27 local_query.limit(40); 29 local_query.limit(QUERY_SEARCH_LIMIT);
28 local_query 30 local_query
29 }, 31 },
30 import_map::Query::new(name_to_import) 32 import_map::Query::new(name_to_import)
31 .limit(40) 33 .limit(QUERY_SEARCH_LIMIT)
32 .name_only() 34 .name_only()
33 .search_mode(import_map::SearchMode::Equals) 35 .search_mode(import_map::SearchMode::Equals)
34 .case_sensitive(), 36 .case_sensitive(),