aboutsummaryrefslogtreecommitdiff
path: root/crates/ide_db/src/helpers
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ide_db/src/helpers')
-rw-r--r--crates/ide_db/src/helpers/import_assets.rs267
-rw-r--r--crates/ide_db/src/helpers/insert_use.rs6
2 files changed, 273 insertions, 0 deletions
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),