diff options
Diffstat (limited to 'crates')
-rw-r--r-- | crates/ra_db/src/lib.rs | 4 | ||||
-rw-r--r-- | crates/ra_hir/src/db.rs | 10 | ||||
-rw-r--r-- | crates/ra_hir_def/src/db.rs | 18 | ||||
-rw-r--r-- | crates/ra_hir_def/src/find_path.rs | 202 | ||||
-rw-r--r-- | crates/ra_hir_def/src/import_map.rs | 331 | ||||
-rw-r--r-- | crates/ra_hir_def/src/item_scope.rs | 23 | ||||
-rw-r--r-- | crates/ra_hir_def/src/lib.rs | 1 | ||||
-rw-r--r-- | crates/ra_hir_def/src/path.rs | 13 | ||||
-rw-r--r-- | crates/ra_hir_def/src/per_ns.rs | 10 | ||||
-rw-r--r-- | crates/ra_ide/src/hover.rs | 148 | ||||
-rw-r--r-- | crates/ra_ide/src/lib.rs | 2 | ||||
-rw-r--r-- | crates/ra_ide_db/src/change.rs | 1 | ||||
-rw-r--r-- | crates/ra_ide_db/src/defs.rs | 2 | ||||
-rw-r--r-- | crates/rust-analyzer/src/config.rs | 29 | ||||
-rw-r--r-- | crates/rust-analyzer/src/lsp_ext.rs | 32 | ||||
-rw-r--r-- | crates/rust-analyzer/src/main_loop.rs | 2 | ||||
-rw-r--r-- | crates/rust-analyzer/src/main_loop/handlers.rs | 129 |
17 files changed, 795 insertions, 162 deletions
diff --git a/crates/ra_db/src/lib.rs b/crates/ra_db/src/lib.rs index 7354b3832..91e0ee619 100644 --- a/crates/ra_db/src/lib.rs +++ b/crates/ra_db/src/lib.rs | |||
@@ -11,8 +11,8 @@ use ra_syntax::{ast, Parse, SourceFile, TextRange, TextSize}; | |||
11 | pub use crate::{ | 11 | pub use crate::{ |
12 | cancellation::Canceled, | 12 | cancellation::Canceled, |
13 | input::{ | 13 | input::{ |
14 | CrateGraph, CrateId, CrateName, Dependency, Edition, Env, ExternSource, ExternSourceId, | 14 | CrateData, CrateGraph, CrateId, CrateName, Dependency, Edition, Env, ExternSource, |
15 | FileId, ProcMacroId, SourceRoot, SourceRootId, | 15 | ExternSourceId, FileId, ProcMacroId, SourceRoot, SourceRootId, |
16 | }, | 16 | }, |
17 | }; | 17 | }; |
18 | pub use relative_path::{RelativePath, RelativePathBuf}; | 18 | pub use relative_path::{RelativePath, RelativePathBuf}; |
diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs index ec931b34f..098b66529 100644 --- a/crates/ra_hir/src/db.rs +++ b/crates/ra_hir/src/db.rs | |||
@@ -3,11 +3,11 @@ | |||
3 | pub use hir_def::db::{ | 3 | pub use hir_def::db::{ |
4 | AttrsQuery, BodyQuery, BodyWithSourceMapQuery, ConstDataQuery, CrateDefMapQueryQuery, | 4 | AttrsQuery, BodyQuery, BodyWithSourceMapQuery, ConstDataQuery, CrateDefMapQueryQuery, |
5 | CrateLangItemsQuery, DefDatabase, DefDatabaseStorage, DocumentationQuery, EnumDataQuery, | 5 | CrateLangItemsQuery, DefDatabase, DefDatabaseStorage, DocumentationQuery, EnumDataQuery, |
6 | ExprScopesQuery, FunctionDataQuery, GenericParamsQuery, ImplDataQuery, InternConstQuery, | 6 | ExprScopesQuery, FunctionDataQuery, GenericParamsQuery, ImplDataQuery, ImportMapQuery, |
7 | InternDatabase, InternDatabaseStorage, InternEnumQuery, InternFunctionQuery, InternImplQuery, | 7 | InternConstQuery, InternDatabase, InternDatabaseStorage, InternEnumQuery, InternFunctionQuery, |
8 | InternStaticQuery, InternStructQuery, InternTraitQuery, InternTypeAliasQuery, InternUnionQuery, | 8 | InternImplQuery, InternStaticQuery, InternStructQuery, InternTraitQuery, InternTypeAliasQuery, |
9 | LangItemQuery, ModuleLangItemsQuery, RawItemsQuery, StaticDataQuery, StructDataQuery, | 9 | InternUnionQuery, LangItemQuery, ModuleLangItemsQuery, RawItemsQuery, StaticDataQuery, |
10 | TraitDataQuery, TypeAliasDataQuery, UnionDataQuery, | 10 | StructDataQuery, TraitDataQuery, TypeAliasDataQuery, UnionDataQuery, |
11 | }; | 11 | }; |
12 | pub use hir_expand::db::{ | 12 | pub use hir_expand::db::{ |
13 | AstDatabase, AstDatabaseStorage, AstIdMapQuery, InternEagerExpansionQuery, InternMacroQuery, | 13 | AstDatabase, AstDatabaseStorage, AstIdMapQuery, InternEagerExpansionQuery, InternMacroQuery, |
diff --git a/crates/ra_hir_def/src/db.rs b/crates/ra_hir_def/src/db.rs index 945a0025e..10cc26480 100644 --- a/crates/ra_hir_def/src/db.rs +++ b/crates/ra_hir_def/src/db.rs | |||
@@ -1,7 +1,7 @@ | |||
1 | //! Defines database & queries for name resolution. | 1 | //! Defines database & queries for name resolution. |
2 | use std::sync::Arc; | 2 | use std::sync::Arc; |
3 | 3 | ||
4 | use hir_expand::{db::AstDatabase, name::Name, HirFileId}; | 4 | use hir_expand::{db::AstDatabase, HirFileId}; |
5 | use ra_db::{salsa, CrateId, SourceDatabase, Upcast}; | 5 | use ra_db::{salsa, CrateId, SourceDatabase, Upcast}; |
6 | use ra_prof::profile; | 6 | use ra_prof::profile; |
7 | use ra_syntax::SmolStr; | 7 | use ra_syntax::SmolStr; |
@@ -12,13 +12,10 @@ use crate::{ | |||
12 | body::{scope::ExprScopes, Body, BodySourceMap}, | 12 | body::{scope::ExprScopes, Body, BodySourceMap}, |
13 | data::{ConstData, FunctionData, ImplData, StaticData, TraitData, TypeAliasData}, | 13 | data::{ConstData, FunctionData, ImplData, StaticData, TraitData, TypeAliasData}, |
14 | docs::Documentation, | 14 | docs::Documentation, |
15 | find_path, | ||
16 | generics::GenericParams, | 15 | generics::GenericParams, |
17 | item_scope::ItemInNs, | 16 | import_map::ImportMap, |
18 | lang_item::{LangItemTarget, LangItems}, | 17 | lang_item::{LangItemTarget, LangItems}, |
19 | nameres::{raw::RawItems, CrateDefMap}, | 18 | nameres::{raw::RawItems, CrateDefMap}, |
20 | path::ModPath, | ||
21 | visibility::Visibility, | ||
22 | AttrDefId, ConstId, ConstLoc, DefWithBodyId, EnumId, EnumLoc, FunctionId, FunctionLoc, | 19 | AttrDefId, ConstId, ConstLoc, DefWithBodyId, EnumId, EnumLoc, FunctionId, FunctionLoc, |
23 | GenericDefId, ImplId, ImplLoc, ModuleId, StaticId, StaticLoc, StructId, StructLoc, TraitId, | 20 | GenericDefId, ImplId, ImplLoc, ModuleId, StaticId, StaticLoc, StructId, StructLoc, TraitId, |
24 | TraitLoc, TypeAliasId, TypeAliasLoc, UnionId, UnionLoc, | 21 | TraitLoc, TypeAliasId, TypeAliasLoc, UnionId, UnionLoc, |
@@ -113,15 +110,8 @@ pub trait DefDatabase: InternDatabase + AstDatabase + Upcast<dyn AstDatabase> { | |||
113 | #[salsa::invoke(Documentation::documentation_query)] | 110 | #[salsa::invoke(Documentation::documentation_query)] |
114 | fn documentation(&self, def: AttrDefId) -> Option<Documentation>; | 111 | fn documentation(&self, def: AttrDefId) -> Option<Documentation>; |
115 | 112 | ||
116 | #[salsa::invoke(find_path::importable_locations_of_query)] | 113 | #[salsa::invoke(ImportMap::import_map_query)] |
117 | fn importable_locations_of( | 114 | fn import_map(&self, krate: CrateId) -> Arc<ImportMap>; |
118 | &self, | ||
119 | item: ItemInNs, | ||
120 | krate: CrateId, | ||
121 | ) -> Arc<[(ModuleId, Name, Visibility)]>; | ||
122 | |||
123 | #[salsa::invoke(find_path::find_path_inner_query)] | ||
124 | fn find_path_inner(&self, item: ItemInNs, from: ModuleId, max_len: usize) -> Option<ModPath>; | ||
125 | } | 115 | } |
126 | 116 | ||
127 | fn crate_def_map_wait(db: &impl DefDatabase, krate: CrateId) -> Arc<CrateDefMap> { | 117 | fn crate_def_map_wait(db: &impl DefDatabase, krate: CrateId) -> Arc<CrateDefMap> { |
diff --git a/crates/ra_hir_def/src/find_path.rs b/crates/ra_hir_def/src/find_path.rs index 4db798473..a7f59e028 100644 --- a/crates/ra_hir_def/src/find_path.rs +++ b/crates/ra_hir_def/src/find_path.rs | |||
@@ -1,9 +1,8 @@ | |||
1 | //! An algorithm to find a path to refer to a certain item. | 1 | //! An algorithm to find a path to refer to a certain item. |
2 | 2 | ||
3 | use std::sync::Arc; | ||
4 | |||
5 | use hir_expand::name::{known, AsName, Name}; | 3 | use hir_expand::name::{known, AsName, Name}; |
6 | use ra_prof::profile; | 4 | use ra_prof::profile; |
5 | use rustc_hash::FxHashSet; | ||
7 | use test_utils::mark; | 6 | use test_utils::mark; |
8 | 7 | ||
9 | use crate::{ | 8 | use crate::{ |
@@ -11,7 +10,7 @@ use crate::{ | |||
11 | item_scope::ItemInNs, | 10 | item_scope::ItemInNs, |
12 | path::{ModPath, PathKind}, | 11 | path::{ModPath, PathKind}, |
13 | visibility::Visibility, | 12 | visibility::Visibility, |
14 | CrateId, ModuleDefId, ModuleId, | 13 | ModuleDefId, ModuleId, |
15 | }; | 14 | }; |
16 | 15 | ||
17 | // FIXME: handle local items | 16 | // FIXME: handle local items |
@@ -20,7 +19,7 @@ use crate::{ | |||
20 | /// *from where* you're referring to the item, hence the `from` parameter. | 19 | /// *from where* you're referring to the item, hence the `from` parameter. |
21 | pub fn find_path(db: &dyn DefDatabase, item: ItemInNs, from: ModuleId) -> Option<ModPath> { | 20 | pub fn find_path(db: &dyn DefDatabase, item: ItemInNs, from: ModuleId) -> Option<ModPath> { |
22 | let _p = profile("find_path"); | 21 | let _p = profile("find_path"); |
23 | db.find_path_inner(item, from, MAX_PATH_LEN) | 22 | find_path_inner(db, item, from, MAX_PATH_LEN) |
24 | } | 23 | } |
25 | 24 | ||
26 | const MAX_PATH_LEN: usize = 15; | 25 | const MAX_PATH_LEN: usize = 15; |
@@ -36,20 +35,9 @@ impl ModPath { | |||
36 | let first_segment = self.segments.first(); | 35 | let first_segment = self.segments.first(); |
37 | first_segment == Some(&known::alloc) || first_segment == Some(&known::core) | 36 | first_segment == Some(&known::alloc) || first_segment == Some(&known::core) |
38 | } | 37 | } |
39 | |||
40 | fn len(&self) -> usize { | ||
41 | self.segments.len() | ||
42 | + match self.kind { | ||
43 | PathKind::Plain => 0, | ||
44 | PathKind::Super(i) => i as usize, | ||
45 | PathKind::Crate => 1, | ||
46 | PathKind::Abs => 0, | ||
47 | PathKind::DollarCrate(_) => 1, | ||
48 | } | ||
49 | } | ||
50 | } | 38 | } |
51 | 39 | ||
52 | pub(crate) fn find_path_inner_query( | 40 | fn find_path_inner( |
53 | db: &dyn DefDatabase, | 41 | db: &dyn DefDatabase, |
54 | item: ItemInNs, | 42 | item: ItemInNs, |
55 | from: ModuleId, | 43 | from: ModuleId, |
@@ -133,31 +121,61 @@ pub(crate) fn find_path_inner_query( | |||
133 | } | 121 | } |
134 | 122 | ||
135 | // - otherwise, look for modules containing (reexporting) it and import it from one of those | 123 | // - otherwise, look for modules containing (reexporting) it and import it from one of those |
124 | |||
136 | let crate_root = ModuleId { local_id: def_map.root, krate: from.krate }; | 125 | let crate_root = ModuleId { local_id: def_map.root, krate: from.krate }; |
137 | let crate_attrs = db.attrs(crate_root.into()); | 126 | let crate_attrs = db.attrs(crate_root.into()); |
138 | let prefer_no_std = crate_attrs.by_key("no_std").exists(); | 127 | let prefer_no_std = crate_attrs.by_key("no_std").exists(); |
139 | let importable_locations = find_importable_locations(db, item, from); | ||
140 | let mut best_path = None; | 128 | let mut best_path = None; |
141 | let mut best_path_len = max_len; | 129 | let mut best_path_len = max_len; |
142 | for (module_id, name) in importable_locations { | ||
143 | let mut path = match db.find_path_inner( | ||
144 | ItemInNs::Types(ModuleDefId::ModuleId(module_id)), | ||
145 | from, | ||
146 | best_path_len - 1, | ||
147 | ) { | ||
148 | None => continue, | ||
149 | Some(path) => path, | ||
150 | }; | ||
151 | path.segments.push(name); | ||
152 | 130 | ||
153 | let new_path = if let Some(best_path) = best_path { | 131 | if item.krate(db) == Some(from.krate) { |
154 | select_best_path(best_path, path, prefer_no_std) | 132 | // Item was defined in the same crate that wants to import it. It cannot be found in any |
155 | } else { | 133 | // dependency in this case. |
156 | path | 134 | |
157 | }; | 135 | let local_imports = find_local_import_locations(db, item, from); |
158 | best_path_len = new_path.len(); | 136 | for (module_id, name) in local_imports { |
159 | best_path = Some(new_path); | 137 | if let Some(mut path) = find_path_inner( |
138 | db, | ||
139 | ItemInNs::Types(ModuleDefId::ModuleId(module_id)), | ||
140 | from, | ||
141 | best_path_len - 1, | ||
142 | ) { | ||
143 | path.segments.push(name); | ||
144 | |||
145 | let new_path = if let Some(best_path) = best_path { | ||
146 | select_best_path(best_path, path, prefer_no_std) | ||
147 | } else { | ||
148 | path | ||
149 | }; | ||
150 | best_path_len = new_path.len(); | ||
151 | best_path = Some(new_path); | ||
152 | } | ||
153 | } | ||
154 | } else { | ||
155 | // Item was defined in some upstream crate. This means that it must be exported from one, | ||
156 | // too (unless we can't name it at all). It could *also* be (re)exported by the same crate | ||
157 | // that wants to import it here, but we always prefer to use the external path here. | ||
158 | |||
159 | let crate_graph = db.crate_graph(); | ||
160 | let extern_paths = crate_graph[from.krate].dependencies.iter().filter_map(|dep| { | ||
161 | let import_map = db.import_map(dep.crate_id); | ||
162 | import_map.path_of(item).map(|modpath| { | ||
163 | let mut modpath = modpath.clone(); | ||
164 | modpath.segments.insert(0, dep.as_name()); | ||
165 | modpath | ||
166 | }) | ||
167 | }); | ||
168 | |||
169 | for path in extern_paths { | ||
170 | let new_path = if let Some(best_path) = best_path { | ||
171 | select_best_path(best_path, path, prefer_no_std) | ||
172 | } else { | ||
173 | path | ||
174 | }; | ||
175 | best_path = Some(new_path); | ||
176 | } | ||
160 | } | 177 | } |
178 | |||
161 | best_path | 179 | best_path |
162 | } | 180 | } |
163 | 181 | ||
@@ -185,69 +203,86 @@ fn select_best_path(old_path: ModPath, new_path: ModPath, prefer_no_std: bool) - | |||
185 | } | 203 | } |
186 | } | 204 | } |
187 | 205 | ||
188 | fn find_importable_locations( | 206 | /// Finds locations in `from.krate` from which `item` can be imported by `from`. |
207 | fn find_local_import_locations( | ||
189 | db: &dyn DefDatabase, | 208 | db: &dyn DefDatabase, |
190 | item: ItemInNs, | 209 | item: ItemInNs, |
191 | from: ModuleId, | 210 | from: ModuleId, |
192 | ) -> Vec<(ModuleId, Name)> { | 211 | ) -> Vec<(ModuleId, Name)> { |
193 | let crate_graph = db.crate_graph(); | 212 | let _p = profile("find_local_import_locations"); |
194 | let mut result = Vec::new(); | 213 | |
195 | // We only look in the crate from which we are importing, and the direct | 214 | // `from` can import anything below `from` with visibility of at least `from`, and anything |
196 | // dependencies. We cannot refer to names from transitive dependencies | 215 | // above `from` with any visibility. That means we do not need to descend into private siblings |
197 | // directly (only through reexports in direct dependencies). | 216 | // of `from` (and similar). |
198 | for krate in Some(from.krate) | 217 | |
199 | .into_iter() | 218 | let def_map = db.crate_def_map(from.krate); |
200 | .chain(crate_graph[from.krate].dependencies.iter().map(|dep| dep.crate_id)) | 219 | |
201 | { | 220 | // Compute the initial worklist. We start with all direct child modules of `from` as well as all |
202 | result.extend( | 221 | // of its (recursive) parent modules. |
203 | db.importable_locations_of(item, krate) | 222 | let data = &def_map.modules[from.local_id]; |
204 | .iter() | 223 | let mut worklist = data |
205 | .filter(|(_, _, vis)| vis.is_visible_from(db, from)) | 224 | .children |
206 | .map(|(m, n, _)| (*m, n.clone())), | 225 | .values() |
207 | ); | 226 | .map(|child| ModuleId { krate: from.krate, local_id: *child }) |
208 | } | 227 | .collect::<Vec<_>>(); |
209 | result | 228 | let mut parent = data.parent; |
210 | } | 229 | while let Some(p) = parent { |
230 | worklist.push(ModuleId { krate: from.krate, local_id: p }); | ||
231 | parent = def_map.modules[p].parent; | ||
232 | } | ||
233 | |||
234 | let mut seen: FxHashSet<_> = FxHashSet::default(); | ||
235 | |||
236 | let mut locations = Vec::new(); | ||
237 | while let Some(module) = worklist.pop() { | ||
238 | if !seen.insert(module) { | ||
239 | continue; // already processed this module | ||
240 | } | ||
241 | |||
242 | let ext_def_map; | ||
243 | let data = if module.krate == from.krate { | ||
244 | &def_map[module.local_id] | ||
245 | } else { | ||
246 | // The crate might reexport a module defined in another crate. | ||
247 | ext_def_map = db.crate_def_map(module.krate); | ||
248 | &ext_def_map[module.local_id] | ||
249 | }; | ||
211 | 250 | ||
212 | /// Collects all locations from which we might import the item in a particular | ||
213 | /// crate. These include the original definition of the item, and any | ||
214 | /// non-private `use`s. | ||
215 | /// | ||
216 | /// Note that the crate doesn't need to be the one in which the item is defined; | ||
217 | /// it might be re-exported in other crates. | ||
218 | pub(crate) fn importable_locations_of_query( | ||
219 | db: &dyn DefDatabase, | ||
220 | item: ItemInNs, | ||
221 | krate: CrateId, | ||
222 | ) -> Arc<[(ModuleId, Name, Visibility)]> { | ||
223 | let _p = profile("importable_locations_of_query"); | ||
224 | let def_map = db.crate_def_map(krate); | ||
225 | let mut result = Vec::new(); | ||
226 | for (local_id, data) in def_map.modules.iter() { | ||
227 | if let Some((name, vis)) = data.scope.name_of(item) { | 251 | if let Some((name, vis)) = data.scope.name_of(item) { |
228 | let is_private = if let Visibility::Module(private_to) = vis { | 252 | if vis.is_visible_from(db, from) { |
229 | private_to.local_id == local_id | 253 | let is_private = if let Visibility::Module(private_to) = vis { |
230 | } else { | 254 | private_to.local_id == module.local_id |
231 | false | 255 | } else { |
232 | }; | 256 | false |
233 | let is_original_def = if let Some(module_def_id) = item.as_module_def_id() { | 257 | }; |
234 | data.scope.declarations().any(|it| it == module_def_id) | 258 | let is_original_def = if let Some(module_def_id) = item.as_module_def_id() { |
235 | } else { | 259 | data.scope.declarations().any(|it| it == module_def_id) |
236 | false | 260 | } else { |
237 | }; | 261 | false |
238 | if is_private && !is_original_def { | 262 | }; |
263 | |||
239 | // Ignore private imports. these could be used if we are | 264 | // Ignore private imports. these could be used if we are |
240 | // in a submodule of this module, but that's usually not | 265 | // in a submodule of this module, but that's usually not |
241 | // what the user wants; and if this module can import | 266 | // what the user wants; and if this module can import |
242 | // the item and we're a submodule of it, so can we. | 267 | // the item and we're a submodule of it, so can we. |
243 | // Also this keeps the cached data smaller. | 268 | // Also this keeps the cached data smaller. |
244 | continue; | 269 | if !is_private || is_original_def { |
270 | locations.push((module, name.clone())); | ||
271 | } | ||
272 | } | ||
273 | } | ||
274 | |||
275 | // Descend into all modules visible from `from`. | ||
276 | for (_, per_ns) in data.scope.entries() { | ||
277 | if let Some((ModuleDefId::ModuleId(module), vis)) = per_ns.take_types_vis() { | ||
278 | if vis.is_visible_from(db, from) { | ||
279 | worklist.push(module); | ||
280 | } | ||
245 | } | 281 | } |
246 | result.push((ModuleId { krate, local_id }, name.clone(), vis)); | ||
247 | } | 282 | } |
248 | } | 283 | } |
249 | 284 | ||
250 | Arc::from(result) | 285 | locations |
251 | } | 286 | } |
252 | 287 | ||
253 | #[cfg(test)] | 288 | #[cfg(test)] |
@@ -385,6 +420,7 @@ mod tests { | |||
385 | 420 | ||
386 | #[test] | 421 | #[test] |
387 | fn different_crate_renamed() { | 422 | fn different_crate_renamed() { |
423 | // Even if a local path exists, if the item is defined externally, prefer an external path. | ||
388 | let code = r#" | 424 | let code = r#" |
389 | //- /main.rs crate:main deps:std | 425 | //- /main.rs crate:main deps:std |
390 | extern crate std as std_renamed; | 426 | extern crate std as std_renamed; |
@@ -392,7 +428,7 @@ mod tests { | |||
392 | //- /std.rs crate:std | 428 | //- /std.rs crate:std |
393 | pub struct S; | 429 | pub struct S; |
394 | "#; | 430 | "#; |
395 | check_found_path(code, "std_renamed::S"); | 431 | check_found_path(code, "std::S"); |
396 | } | 432 | } |
397 | 433 | ||
398 | #[test] | 434 | #[test] |
diff --git a/crates/ra_hir_def/src/import_map.rs b/crates/ra_hir_def/src/import_map.rs new file mode 100644 index 000000000..4284a0a91 --- /dev/null +++ b/crates/ra_hir_def/src/import_map.rs | |||
@@ -0,0 +1,331 @@ | |||
1 | //! A map of all publicly exported items in a crate. | ||
2 | |||
3 | use std::{collections::hash_map::Entry, fmt, sync::Arc}; | ||
4 | |||
5 | use ra_db::CrateId; | ||
6 | use rustc_hash::FxHashMap; | ||
7 | |||
8 | use crate::{ | ||
9 | db::DefDatabase, | ||
10 | item_scope::ItemInNs, | ||
11 | path::{ModPath, PathKind}, | ||
12 | visibility::Visibility, | ||
13 | ModuleDefId, ModuleId, | ||
14 | }; | ||
15 | |||
16 | /// A map from publicly exported items to the path needed to import/name them from a downstream | ||
17 | /// crate. | ||
18 | /// | ||
19 | /// Reexports of items are taken into account, ie. if something is exported under multiple | ||
20 | /// names, the one with the shortest import path will be used. | ||
21 | /// | ||
22 | /// Note that all paths are relative to the containing crate's root, so the crate name still needs | ||
23 | /// to be prepended to the `ModPath` before the path is valid. | ||
24 | #[derive(Eq, PartialEq)] | ||
25 | pub struct ImportMap { | ||
26 | map: FxHashMap<ItemInNs, ModPath>, | ||
27 | } | ||
28 | |||
29 | impl ImportMap { | ||
30 | pub fn import_map_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<Self> { | ||
31 | let _p = ra_prof::profile("import_map_query"); | ||
32 | let def_map = db.crate_def_map(krate); | ||
33 | let mut import_map = FxHashMap::with_capacity_and_hasher(64, Default::default()); | ||
34 | |||
35 | // We look only into modules that are public(ly reexported), starting with the crate root. | ||
36 | let empty = ModPath { kind: PathKind::Plain, segments: vec![] }; | ||
37 | let root = ModuleId { krate, local_id: def_map.root }; | ||
38 | let mut worklist = vec![(root, empty)]; | ||
39 | while let Some((module, mod_path)) = worklist.pop() { | ||
40 | let ext_def_map; | ||
41 | let mod_data = if module.krate == krate { | ||
42 | &def_map[module.local_id] | ||
43 | } else { | ||
44 | // The crate might reexport a module defined in another crate. | ||
45 | ext_def_map = db.crate_def_map(module.krate); | ||
46 | &ext_def_map[module.local_id] | ||
47 | }; | ||
48 | |||
49 | let visible_items = mod_data.scope.entries().filter_map(|(name, per_ns)| { | ||
50 | let per_ns = per_ns.filter_visibility(|vis| vis == Visibility::Public); | ||
51 | if per_ns.is_none() { | ||
52 | None | ||
53 | } else { | ||
54 | Some((name, per_ns)) | ||
55 | } | ||
56 | }); | ||
57 | |||
58 | for (name, per_ns) in visible_items { | ||
59 | let mk_path = || { | ||
60 | let mut path = mod_path.clone(); | ||
61 | path.segments.push(name.clone()); | ||
62 | path | ||
63 | }; | ||
64 | |||
65 | for item in per_ns.iter_items() { | ||
66 | let path = mk_path(); | ||
67 | match import_map.entry(item) { | ||
68 | Entry::Vacant(entry) => { | ||
69 | entry.insert(path); | ||
70 | } | ||
71 | Entry::Occupied(mut entry) => { | ||
72 | // If the new path is shorter, prefer that one. | ||
73 | if path.len() < entry.get().len() { | ||
74 | *entry.get_mut() = path; | ||
75 | } else { | ||
76 | continue; | ||
77 | } | ||
78 | } | ||
79 | } | ||
80 | |||
81 | // If we've just added a path to a module, descend into it. We might traverse | ||
82 | // modules multiple times, but only if the new path to it is shorter than the | ||
83 | // first (else we `continue` above). | ||
84 | if let Some(ModuleDefId::ModuleId(mod_id)) = item.as_module_def_id() { | ||
85 | worklist.push((mod_id, mk_path())); | ||
86 | } | ||
87 | } | ||
88 | } | ||
89 | } | ||
90 | |||
91 | Arc::new(Self { map: import_map }) | ||
92 | } | ||
93 | |||
94 | /// Returns the `ModPath` needed to import/mention `item`, relative to this crate's root. | ||
95 | pub fn path_of(&self, item: ItemInNs) -> Option<&ModPath> { | ||
96 | self.map.get(&item) | ||
97 | } | ||
98 | } | ||
99 | |||
100 | impl fmt::Debug for ImportMap { | ||
101 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
102 | let mut importable_paths: Vec<_> = self | ||
103 | .map | ||
104 | .iter() | ||
105 | .map(|(item, modpath)| { | ||
106 | let ns = match item { | ||
107 | ItemInNs::Types(_) => "t", | ||
108 | ItemInNs::Values(_) => "v", | ||
109 | ItemInNs::Macros(_) => "m", | ||
110 | }; | ||
111 | format!("- {} ({})", modpath, ns) | ||
112 | }) | ||
113 | .collect(); | ||
114 | |||
115 | importable_paths.sort(); | ||
116 | f.write_str(&importable_paths.join("\n")) | ||
117 | } | ||
118 | } | ||
119 | |||
120 | #[cfg(test)] | ||
121 | mod tests { | ||
122 | use super::*; | ||
123 | use crate::test_db::TestDB; | ||
124 | use insta::assert_snapshot; | ||
125 | use ra_db::fixture::WithFixture; | ||
126 | use ra_db::SourceDatabase; | ||
127 | |||
128 | fn import_map(ra_fixture: &str) -> String { | ||
129 | let db = TestDB::with_files(ra_fixture); | ||
130 | let crate_graph = db.crate_graph(); | ||
131 | |||
132 | let import_maps: Vec<_> = crate_graph | ||
133 | .iter() | ||
134 | .filter_map(|krate| { | ||
135 | let cdata = &crate_graph[krate]; | ||
136 | let name = cdata.display_name.as_ref()?; | ||
137 | |||
138 | let map = db.import_map(krate); | ||
139 | |||
140 | Some(format!("{}:\n{:?}", name, map)) | ||
141 | }) | ||
142 | .collect(); | ||
143 | |||
144 | import_maps.join("\n") | ||
145 | } | ||
146 | |||
147 | #[test] | ||
148 | fn smoke() { | ||
149 | let map = import_map( | ||
150 | r" | ||
151 | //- /main.rs crate:main deps:lib | ||
152 | |||
153 | mod private { | ||
154 | pub use lib::Pub; | ||
155 | pub struct InPrivateModule; | ||
156 | } | ||
157 | |||
158 | pub mod publ1 { | ||
159 | use lib::Pub; | ||
160 | } | ||
161 | |||
162 | pub mod real_pub { | ||
163 | pub use lib::Pub; | ||
164 | } | ||
165 | pub mod real_pu2 { // same path length as above | ||
166 | pub use lib::Pub; | ||
167 | } | ||
168 | |||
169 | //- /lib.rs crate:lib | ||
170 | pub struct Pub {} | ||
171 | pub struct Pub2; // t + v | ||
172 | struct Priv; | ||
173 | ", | ||
174 | ); | ||
175 | |||
176 | assert_snapshot!(map, @r###" | ||
177 | main: | ||
178 | - publ1 (t) | ||
179 | - real_pu2 (t) | ||
180 | - real_pub (t) | ||
181 | - real_pub::Pub (t) | ||
182 | lib: | ||
183 | - Pub (t) | ||
184 | - Pub2 (t) | ||
185 | - Pub2 (v) | ||
186 | "###); | ||
187 | } | ||
188 | |||
189 | #[test] | ||
190 | fn prefers_shortest_path() { | ||
191 | let map = import_map( | ||
192 | r" | ||
193 | //- /main.rs crate:main | ||
194 | |||
195 | pub mod sub { | ||
196 | pub mod subsub { | ||
197 | pub struct Def {} | ||
198 | } | ||
199 | |||
200 | pub use super::sub::subsub::Def; | ||
201 | } | ||
202 | ", | ||
203 | ); | ||
204 | |||
205 | assert_snapshot!(map, @r###" | ||
206 | main: | ||
207 | - sub (t) | ||
208 | - sub::Def (t) | ||
209 | - sub::subsub (t) | ||
210 | "###); | ||
211 | } | ||
212 | |||
213 | #[test] | ||
214 | fn type_reexport_cross_crate() { | ||
215 | // Reexports need to be visible from a crate, even if the original crate exports the item | ||
216 | // at a shorter path. | ||
217 | let map = import_map( | ||
218 | r" | ||
219 | //- /main.rs crate:main deps:lib | ||
220 | pub mod m { | ||
221 | pub use lib::S; | ||
222 | } | ||
223 | //- /lib.rs crate:lib | ||
224 | pub struct S; | ||
225 | ", | ||
226 | ); | ||
227 | |||
228 | assert_snapshot!(map, @r###" | ||
229 | main: | ||
230 | - m (t) | ||
231 | - m::S (t) | ||
232 | - m::S (v) | ||
233 | lib: | ||
234 | - S (t) | ||
235 | - S (v) | ||
236 | "###); | ||
237 | } | ||
238 | |||
239 | #[test] | ||
240 | fn macro_reexport() { | ||
241 | let map = import_map( | ||
242 | r" | ||
243 | //- /main.rs crate:main deps:lib | ||
244 | pub mod m { | ||
245 | pub use lib::pub_macro; | ||
246 | } | ||
247 | //- /lib.rs crate:lib | ||
248 | #[macro_export] | ||
249 | macro_rules! pub_macro { | ||
250 | () => {}; | ||
251 | } | ||
252 | ", | ||
253 | ); | ||
254 | |||
255 | assert_snapshot!(map, @r###" | ||
256 | main: | ||
257 | - m (t) | ||
258 | - m::pub_macro (m) | ||
259 | lib: | ||
260 | - pub_macro (m) | ||
261 | "###); | ||
262 | } | ||
263 | |||
264 | #[test] | ||
265 | fn module_reexport() { | ||
266 | // Reexporting modules from a dependency adds all contents to the import map. | ||
267 | let map = import_map( | ||
268 | r" | ||
269 | //- /main.rs crate:main deps:lib | ||
270 | pub use lib::module as reexported_module; | ||
271 | //- /lib.rs crate:lib | ||
272 | pub mod module { | ||
273 | pub struct S; | ||
274 | } | ||
275 | ", | ||
276 | ); | ||
277 | |||
278 | assert_snapshot!(map, @r###" | ||
279 | main: | ||
280 | - reexported_module (t) | ||
281 | - reexported_module::S (t) | ||
282 | - reexported_module::S (v) | ||
283 | lib: | ||
284 | - module (t) | ||
285 | - module::S (t) | ||
286 | - module::S (v) | ||
287 | "###); | ||
288 | } | ||
289 | |||
290 | #[test] | ||
291 | fn cyclic_module_reexport() { | ||
292 | // A cyclic reexport does not hang. | ||
293 | let map = import_map( | ||
294 | r" | ||
295 | //- /lib.rs crate:lib | ||
296 | pub mod module { | ||
297 | pub struct S; | ||
298 | pub use super::sub::*; | ||
299 | } | ||
300 | |||
301 | pub mod sub { | ||
302 | pub use super::module; | ||
303 | } | ||
304 | ", | ||
305 | ); | ||
306 | |||
307 | assert_snapshot!(map, @r###" | ||
308 | lib: | ||
309 | - module (t) | ||
310 | - module::S (t) | ||
311 | - module::S (v) | ||
312 | - sub (t) | ||
313 | "###); | ||
314 | } | ||
315 | |||
316 | #[test] | ||
317 | fn private_macro() { | ||
318 | let map = import_map( | ||
319 | r" | ||
320 | //- /lib.rs crate:lib | ||
321 | macro_rules! private_macro { | ||
322 | () => {}; | ||
323 | } | ||
324 | ", | ||
325 | ); | ||
326 | |||
327 | assert_snapshot!(map, @r###" | ||
328 | lib: | ||
329 | "###); | ||
330 | } | ||
331 | } | ||
diff --git a/crates/ra_hir_def/src/item_scope.rs b/crates/ra_hir_def/src/item_scope.rs index fc15948ad..b03ba939a 100644 --- a/crates/ra_hir_def/src/item_scope.rs +++ b/crates/ra_hir_def/src/item_scope.rs | |||
@@ -3,11 +3,12 @@ | |||
3 | 3 | ||
4 | use hir_expand::name::Name; | 4 | use hir_expand::name::Name; |
5 | use once_cell::sync::Lazy; | 5 | use once_cell::sync::Lazy; |
6 | use ra_db::CrateId; | ||
6 | use rustc_hash::FxHashMap; | 7 | use rustc_hash::FxHashMap; |
7 | 8 | ||
8 | use crate::{ | 9 | use crate::{ |
9 | per_ns::PerNs, visibility::Visibility, AdtId, BuiltinType, ImplId, MacroDefId, ModuleDefId, | 10 | db::DefDatabase, per_ns::PerNs, visibility::Visibility, AdtId, BuiltinType, HasModule, ImplId, |
10 | TraitId, | 11 | Lookup, MacroDefId, ModuleDefId, TraitId, |
11 | }; | 12 | }; |
12 | 13 | ||
13 | #[derive(Debug, Default, PartialEq, Eq)] | 14 | #[derive(Debug, Default, PartialEq, Eq)] |
@@ -203,4 +204,22 @@ impl ItemInNs { | |||
203 | ItemInNs::Macros(_) => None, | 204 | ItemInNs::Macros(_) => None, |
204 | } | 205 | } |
205 | } | 206 | } |
207 | |||
208 | /// Returns the crate defining this item (or `None` if `self` is built-in). | ||
209 | pub fn krate(&self, db: &dyn DefDatabase) -> Option<CrateId> { | ||
210 | Some(match self { | ||
211 | ItemInNs::Types(did) | ItemInNs::Values(did) => match did { | ||
212 | ModuleDefId::ModuleId(id) => id.krate, | ||
213 | ModuleDefId::FunctionId(id) => id.lookup(db).module(db).krate, | ||
214 | ModuleDefId::AdtId(id) => id.module(db).krate, | ||
215 | ModuleDefId::EnumVariantId(id) => id.parent.lookup(db).container.module(db).krate, | ||
216 | ModuleDefId::ConstId(id) => id.lookup(db).container.module(db).krate, | ||
217 | ModuleDefId::StaticId(id) => id.lookup(db).container.module(db).krate, | ||
218 | ModuleDefId::TraitId(id) => id.lookup(db).container.module(db).krate, | ||
219 | ModuleDefId::TypeAliasId(id) => id.lookup(db).module(db).krate, | ||
220 | ModuleDefId::BuiltinType(_) => return None, | ||
221 | }, | ||
222 | ItemInNs::Macros(id) => return id.krate, | ||
223 | }) | ||
224 | } | ||
206 | } | 225 | } |
diff --git a/crates/ra_hir_def/src/lib.rs b/crates/ra_hir_def/src/lib.rs index 5325a2760..de490fcc5 100644 --- a/crates/ra_hir_def/src/lib.rs +++ b/crates/ra_hir_def/src/lib.rs | |||
@@ -43,6 +43,7 @@ pub mod child_by_source; | |||
43 | 43 | ||
44 | pub mod visibility; | 44 | pub mod visibility; |
45 | pub mod find_path; | 45 | pub mod find_path; |
46 | pub mod import_map; | ||
46 | 47 | ||
47 | #[cfg(test)] | 48 | #[cfg(test)] |
48 | mod test_db; | 49 | mod test_db; |
diff --git a/crates/ra_hir_def/src/path.rs b/crates/ra_hir_def/src/path.rs index 4512448e0..bfa921de2 100644 --- a/crates/ra_hir_def/src/path.rs +++ b/crates/ra_hir_def/src/path.rs | |||
@@ -76,6 +76,19 @@ impl ModPath { | |||
76 | } | 76 | } |
77 | } | 77 | } |
78 | 78 | ||
79 | /// Returns the number of segments in the path (counting special segments like `$crate` and | ||
80 | /// `super`). | ||
81 | pub fn len(&self) -> usize { | ||
82 | self.segments.len() | ||
83 | + match self.kind { | ||
84 | PathKind::Plain => 0, | ||
85 | PathKind::Super(i) => i as usize, | ||
86 | PathKind::Crate => 1, | ||
87 | PathKind::Abs => 0, | ||
88 | PathKind::DollarCrate(_) => 1, | ||
89 | } | ||
90 | } | ||
91 | |||
79 | pub fn is_ident(&self) -> bool { | 92 | pub fn is_ident(&self) -> bool { |
80 | self.kind == PathKind::Plain && self.segments.len() == 1 | 93 | self.kind == PathKind::Plain && self.segments.len() == 1 |
81 | } | 94 | } |
diff --git a/crates/ra_hir_def/src/per_ns.rs b/crates/ra_hir_def/src/per_ns.rs index 6e435c8c1..74665c588 100644 --- a/crates/ra_hir_def/src/per_ns.rs +++ b/crates/ra_hir_def/src/per_ns.rs | |||
@@ -5,7 +5,7 @@ | |||
5 | 5 | ||
6 | use hir_expand::MacroDefId; | 6 | use hir_expand::MacroDefId; |
7 | 7 | ||
8 | use crate::{visibility::Visibility, ModuleDefId}; | 8 | use crate::{item_scope::ItemInNs, visibility::Visibility, ModuleDefId}; |
9 | 9 | ||
10 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] | 10 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] |
11 | pub struct PerNs { | 11 | pub struct PerNs { |
@@ -84,4 +84,12 @@ impl PerNs { | |||
84 | macros: self.macros.or(other.macros), | 84 | macros: self.macros.or(other.macros), |
85 | } | 85 | } |
86 | } | 86 | } |
87 | |||
88 | pub fn iter_items(self) -> impl Iterator<Item = ItemInNs> { | ||
89 | self.types | ||
90 | .map(|it| ItemInNs::Types(it.0)) | ||
91 | .into_iter() | ||
92 | .chain(self.values.map(|it| ItemInNs::Values(it.0)).into_iter()) | ||
93 | .chain(self.macros.map(|it| ItemInNs::Macros(it.0)).into_iter()) | ||
94 | } | ||
87 | } | 95 | } |
diff --git a/crates/ra_ide/src/hover.rs b/crates/ra_ide/src/hover.rs index 9636cd0d6..62df07459 100644 --- a/crates/ra_ide/src/hover.rs +++ b/crates/ra_ide/src/hover.rs | |||
@@ -13,14 +13,43 @@ use ra_ide_db::{ | |||
13 | use ra_syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxToken, TokenAtOffset}; | 13 | use ra_syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxToken, TokenAtOffset}; |
14 | 14 | ||
15 | use crate::{ | 15 | use crate::{ |
16 | display::{macro_label, rust_code_markup, rust_code_markup_with_doc, ShortLabel}, | 16 | display::{macro_label, rust_code_markup, rust_code_markup_with_doc, ShortLabel, ToNav}, |
17 | FilePosition, RangeInfo, | 17 | FilePosition, NavigationTarget, RangeInfo, |
18 | }; | 18 | }; |
19 | 19 | ||
20 | #[derive(Clone, Debug, PartialEq, Eq)] | ||
21 | pub struct HoverConfig { | ||
22 | pub implementations: bool, | ||
23 | } | ||
24 | |||
25 | impl Default for HoverConfig { | ||
26 | fn default() -> Self { | ||
27 | Self { implementations: true } | ||
28 | } | ||
29 | } | ||
30 | |||
31 | impl HoverConfig { | ||
32 | pub const NO_ACTIONS: Self = Self { implementations: false }; | ||
33 | |||
34 | pub fn any(&self) -> bool { | ||
35 | self.implementations | ||
36 | } | ||
37 | |||
38 | pub fn none(&self) -> bool { | ||
39 | !self.any() | ||
40 | } | ||
41 | } | ||
42 | |||
43 | #[derive(Debug, Clone)] | ||
44 | pub enum HoverAction { | ||
45 | Implementaion(FilePosition), | ||
46 | } | ||
47 | |||
20 | /// Contains the results when hovering over an item | 48 | /// Contains the results when hovering over an item |
21 | #[derive(Debug, Default)] | 49 | #[derive(Debug, Default)] |
22 | pub struct HoverResult { | 50 | pub struct HoverResult { |
23 | results: Vec<String>, | 51 | results: Vec<String>, |
52 | actions: Vec<HoverAction>, | ||
24 | } | 53 | } |
25 | 54 | ||
26 | impl HoverResult { | 55 | impl HoverResult { |
@@ -48,10 +77,20 @@ impl HoverResult { | |||
48 | &self.results | 77 | &self.results |
49 | } | 78 | } |
50 | 79 | ||
80 | pub fn actions(&self) -> &[HoverAction] { | ||
81 | &self.actions | ||
82 | } | ||
83 | |||
84 | pub fn push_action(&mut self, action: HoverAction) { | ||
85 | self.actions.push(action); | ||
86 | } | ||
87 | |||
51 | /// Returns the results converted into markup | 88 | /// Returns the results converted into markup |
52 | /// for displaying in a UI | 89 | /// for displaying in a UI |
90 | /// | ||
91 | /// Does not process actions! | ||
53 | pub fn to_markup(&self) -> String { | 92 | pub fn to_markup(&self) -> String { |
54 | self.results.join("\n\n---\n") | 93 | self.results.join("\n\n___\n") |
55 | } | 94 | } |
56 | } | 95 | } |
57 | 96 | ||
@@ -82,6 +121,10 @@ pub(crate) fn hover(db: &RootDatabase, position: FilePosition) -> Option<RangeIn | |||
82 | res.extend(hover_text_from_name_kind(db, name_kind)); | 121 | res.extend(hover_text_from_name_kind(db, name_kind)); |
83 | 122 | ||
84 | if !res.is_empty() { | 123 | if !res.is_empty() { |
124 | if let Some(action) = show_implementations_action(db, name_kind) { | ||
125 | res.push_action(action); | ||
126 | } | ||
127 | |||
85 | return Some(RangeInfo::new(range, res)); | 128 | return Some(RangeInfo::new(range, res)); |
86 | } | 129 | } |
87 | } | 130 | } |
@@ -112,6 +155,26 @@ pub(crate) fn hover(db: &RootDatabase, position: FilePosition) -> Option<RangeIn | |||
112 | Some(RangeInfo::new(range, res)) | 155 | Some(RangeInfo::new(range, res)) |
113 | } | 156 | } |
114 | 157 | ||
158 | fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> { | ||
159 | fn to_action(nav_target: NavigationTarget) -> HoverAction { | ||
160 | HoverAction::Implementaion(FilePosition { | ||
161 | file_id: nav_target.file_id(), | ||
162 | offset: nav_target.range().start(), | ||
163 | }) | ||
164 | } | ||
165 | |||
166 | match def { | ||
167 | Definition::ModuleDef(it) => match it { | ||
168 | ModuleDef::Adt(Adt::Struct(it)) => Some(to_action(it.to_nav(db))), | ||
169 | ModuleDef::Adt(Adt::Union(it)) => Some(to_action(it.to_nav(db))), | ||
170 | ModuleDef::Adt(Adt::Enum(it)) => Some(to_action(it.to_nav(db))), | ||
171 | ModuleDef::Trait(it) => Some(to_action(it.to_nav(db))), | ||
172 | _ => None, | ||
173 | }, | ||
174 | _ => None, | ||
175 | } | ||
176 | } | ||
177 | |||
115 | fn hover_text( | 178 | fn hover_text( |
116 | docs: Option<String>, | 179 | docs: Option<String>, |
117 | desc: Option<String>, | 180 | desc: Option<String>, |
@@ -228,6 +291,8 @@ fn pick_best(tokens: TokenAtOffset<SyntaxToken>) -> Option<SyntaxToken> { | |||
228 | 291 | ||
229 | #[cfg(test)] | 292 | #[cfg(test)] |
230 | mod tests { | 293 | mod tests { |
294 | use super::*; | ||
295 | |||
231 | use ra_db::FileLoader; | 296 | use ra_db::FileLoader; |
232 | use ra_syntax::TextRange; | 297 | use ra_syntax::TextRange; |
233 | 298 | ||
@@ -241,7 +306,14 @@ mod tests { | |||
241 | s.map(trim_markup) | 306 | s.map(trim_markup) |
242 | } | 307 | } |
243 | 308 | ||
244 | fn check_hover_result(fixture: &str, expected: &[&str]) -> String { | 309 | fn assert_impl_action(action: &HoverAction, position: u32) { |
310 | let offset = match action { | ||
311 | HoverAction::Implementaion(pos) => pos.offset, | ||
312 | }; | ||
313 | assert_eq!(offset, position.into()); | ||
314 | } | ||
315 | |||
316 | fn check_hover_result(fixture: &str, expected: &[&str]) -> (String, Vec<HoverAction>) { | ||
245 | let (analysis, position) = analysis_and_position(fixture); | 317 | let (analysis, position) = analysis_and_position(fixture); |
246 | let hover = analysis.hover(position).unwrap().unwrap(); | 318 | let hover = analysis.hover(position).unwrap().unwrap(); |
247 | let mut results = Vec::from(hover.info.results()); | 319 | let mut results = Vec::from(hover.info.results()); |
@@ -256,7 +328,7 @@ mod tests { | |||
256 | assert_eq!(hover.info.len(), expected.len()); | 328 | assert_eq!(hover.info.len(), expected.len()); |
257 | 329 | ||
258 | let content = analysis.db.file_text(position.file_id); | 330 | let content = analysis.db.file_text(position.file_id); |
259 | content[hover.range].to_string() | 331 | (content[hover.range].to_string(), hover.info.actions().to_vec()) |
260 | } | 332 | } |
261 | 333 | ||
262 | fn check_hover_no_result(fixture: &str) { | 334 | fn check_hover_no_result(fixture: &str) { |
@@ -746,7 +818,7 @@ fn func(foo: i32) { if true { <|>foo; }; } | |||
746 | 818 | ||
747 | #[test] | 819 | #[test] |
748 | fn test_hover_through_macro() { | 820 | fn test_hover_through_macro() { |
749 | let hover_on = check_hover_result( | 821 | let (hover_on, _) = check_hover_result( |
750 | " | 822 | " |
751 | //- /lib.rs | 823 | //- /lib.rs |
752 | macro_rules! id { | 824 | macro_rules! id { |
@@ -767,7 +839,7 @@ fn func(foo: i32) { if true { <|>foo; }; } | |||
767 | 839 | ||
768 | #[test] | 840 | #[test] |
769 | fn test_hover_through_expr_in_macro() { | 841 | fn test_hover_through_expr_in_macro() { |
770 | let hover_on = check_hover_result( | 842 | let (hover_on, _) = check_hover_result( |
771 | " | 843 | " |
772 | //- /lib.rs | 844 | //- /lib.rs |
773 | macro_rules! id { | 845 | macro_rules! id { |
@@ -785,7 +857,7 @@ fn func(foo: i32) { if true { <|>foo; }; } | |||
785 | 857 | ||
786 | #[test] | 858 | #[test] |
787 | fn test_hover_through_expr_in_macro_recursive() { | 859 | fn test_hover_through_expr_in_macro_recursive() { |
788 | let hover_on = check_hover_result( | 860 | let (hover_on, _) = check_hover_result( |
789 | " | 861 | " |
790 | //- /lib.rs | 862 | //- /lib.rs |
791 | macro_rules! id_deep { | 863 | macro_rules! id_deep { |
@@ -806,7 +878,7 @@ fn func(foo: i32) { if true { <|>foo; }; } | |||
806 | 878 | ||
807 | #[test] | 879 | #[test] |
808 | fn test_hover_through_func_in_macro_recursive() { | 880 | fn test_hover_through_func_in_macro_recursive() { |
809 | let hover_on = check_hover_result( | 881 | let (hover_on, _) = check_hover_result( |
810 | " | 882 | " |
811 | //- /lib.rs | 883 | //- /lib.rs |
812 | macro_rules! id_deep { | 884 | macro_rules! id_deep { |
@@ -830,7 +902,7 @@ fn func(foo: i32) { if true { <|>foo; }; } | |||
830 | 902 | ||
831 | #[test] | 903 | #[test] |
832 | fn test_hover_through_literal_string_in_macro() { | 904 | fn test_hover_through_literal_string_in_macro() { |
833 | let hover_on = check_hover_result( | 905 | let (hover_on, _) = check_hover_result( |
834 | r#" | 906 | r#" |
835 | //- /lib.rs | 907 | //- /lib.rs |
836 | macro_rules! arr { | 908 | macro_rules! arr { |
@@ -849,7 +921,7 @@ fn func(foo: i32) { if true { <|>foo; }; } | |||
849 | 921 | ||
850 | #[test] | 922 | #[test] |
851 | fn test_hover_through_assert_macro() { | 923 | fn test_hover_through_assert_macro() { |
852 | let hover_on = check_hover_result( | 924 | let (hover_on, _) = check_hover_result( |
853 | r#" | 925 | r#" |
854 | //- /lib.rs | 926 | //- /lib.rs |
855 | #[rustc_builtin_macro] | 927 | #[rustc_builtin_macro] |
@@ -925,13 +997,14 @@ fn func(foo: i32) { if true { <|>foo; }; } | |||
925 | 997 | ||
926 | #[test] | 998 | #[test] |
927 | fn test_hover_trait_show_qualifiers() { | 999 | fn test_hover_trait_show_qualifiers() { |
928 | check_hover_result( | 1000 | let (_, actions) = check_hover_result( |
929 | " | 1001 | " |
930 | //- /lib.rs | 1002 | //- /lib.rs |
931 | unsafe trait foo<|>() {} | 1003 | unsafe trait foo<|>() {} |
932 | ", | 1004 | ", |
933 | &["unsafe trait foo"], | 1005 | &["unsafe trait foo"], |
934 | ); | 1006 | ); |
1007 | assert_impl_action(&actions[0], 13); | ||
935 | } | 1008 | } |
936 | 1009 | ||
937 | #[test] | 1010 | #[test] |
@@ -1052,4 +1125,55 @@ fn func(foo: i32) { if true { <|>foo; }; } | |||
1052 | &["Bar\n```\n\n```rust\nfn foo(&self)\n```\n___\n\nDo the foo"], | 1125 | &["Bar\n```\n\n```rust\nfn foo(&self)\n```\n___\n\nDo the foo"], |
1053 | ); | 1126 | ); |
1054 | } | 1127 | } |
1128 | |||
1129 | #[test] | ||
1130 | fn test_hover_trait_has_impl_action() { | ||
1131 | let (_, actions) = check_hover_result( | ||
1132 | " | ||
1133 | //- /lib.rs | ||
1134 | trait foo<|>() {} | ||
1135 | ", | ||
1136 | &["trait foo"], | ||
1137 | ); | ||
1138 | assert_impl_action(&actions[0], 6); | ||
1139 | } | ||
1140 | |||
1141 | #[test] | ||
1142 | fn test_hover_struct_has_impl_action() { | ||
1143 | let (_, actions) = check_hover_result( | ||
1144 | " | ||
1145 | //- /lib.rs | ||
1146 | struct foo<|>() {} | ||
1147 | ", | ||
1148 | &["struct foo"], | ||
1149 | ); | ||
1150 | assert_impl_action(&actions[0], 7); | ||
1151 | } | ||
1152 | |||
1153 | #[test] | ||
1154 | fn test_hover_union_has_impl_action() { | ||
1155 | let (_, actions) = check_hover_result( | ||
1156 | " | ||
1157 | //- /lib.rs | ||
1158 | union foo<|>() {} | ||
1159 | ", | ||
1160 | &["union foo"], | ||
1161 | ); | ||
1162 | assert_impl_action(&actions[0], 6); | ||
1163 | } | ||
1164 | |||
1165 | #[test] | ||
1166 | fn test_hover_enum_has_impl_action() { | ||
1167 | let (_, actions) = check_hover_result( | ||
1168 | " | ||
1169 | //- /lib.rs | ||
1170 | enum foo<|>() { | ||
1171 | A, | ||
1172 | B | ||
1173 | } | ||
1174 | ", | ||
1175 | &["enum foo"], | ||
1176 | ); | ||
1177 | assert_impl_action(&actions[0], 5); | ||
1178 | } | ||
1055 | } | 1179 | } |
diff --git a/crates/ra_ide/src/lib.rs b/crates/ra_ide/src/lib.rs index 34c2d75fe..a56718d3f 100644 --- a/crates/ra_ide/src/lib.rs +++ b/crates/ra_ide/src/lib.rs | |||
@@ -66,7 +66,7 @@ pub use crate::{ | |||
66 | display::{file_structure, FunctionSignature, NavigationTarget, StructureNode}, | 66 | display::{file_structure, FunctionSignature, NavigationTarget, StructureNode}, |
67 | expand_macro::ExpandedMacro, | 67 | expand_macro::ExpandedMacro, |
68 | folding_ranges::{Fold, FoldKind}, | 68 | folding_ranges::{Fold, FoldKind}, |
69 | hover::HoverResult, | 69 | hover::{HoverAction, HoverConfig, HoverResult}, |
70 | inlay_hints::{InlayHint, InlayHintsConfig, InlayKind}, | 70 | inlay_hints::{InlayHint, InlayHintsConfig, InlayKind}, |
71 | references::{Declaration, Reference, ReferenceAccess, ReferenceKind, ReferenceSearchResult}, | 71 | references::{Declaration, Reference, ReferenceAccess, ReferenceKind, ReferenceSearchResult}, |
72 | runnables::{Runnable, RunnableKind, TestId}, | 72 | runnables::{Runnable, RunnableKind, TestId}, |
diff --git a/crates/ra_ide_db/src/change.rs b/crates/ra_ide_db/src/change.rs index 8446ef88e..ea78e49e0 100644 --- a/crates/ra_ide_db/src/change.rs +++ b/crates/ra_ide_db/src/change.rs | |||
@@ -334,6 +334,7 @@ impl RootDatabase { | |||
334 | hir::db::CrateLangItemsQuery | 334 | hir::db::CrateLangItemsQuery |
335 | hir::db::LangItemQuery | 335 | hir::db::LangItemQuery |
336 | hir::db::DocumentationQuery | 336 | hir::db::DocumentationQuery |
337 | hir::db::ImportMapQuery | ||
337 | 338 | ||
338 | // InternDatabase | 339 | // InternDatabase |
339 | hir::db::InternFunctionQuery | 340 | hir::db::InternFunctionQuery |
diff --git a/crates/ra_ide_db/src/defs.rs b/crates/ra_ide_db/src/defs.rs index 8b06cbfc5..1db60b87f 100644 --- a/crates/ra_ide_db/src/defs.rs +++ b/crates/ra_ide_db/src/defs.rs | |||
@@ -18,7 +18,7 @@ use ra_syntax::{ | |||
18 | use crate::RootDatabase; | 18 | use crate::RootDatabase; |
19 | 19 | ||
20 | // FIXME: a more precise name would probably be `Symbol`? | 20 | // FIXME: a more precise name would probably be `Symbol`? |
21 | #[derive(Debug, PartialEq, Eq)] | 21 | #[derive(Debug, PartialEq, Eq, Copy, Clone)] |
22 | pub enum Definition { | 22 | pub enum Definition { |
23 | Macro(MacroDef), | 23 | Macro(MacroDef), |
24 | Field(Field), | 24 | Field(Field), |
diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index 23168c3ae..8d6efdbe8 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs | |||
@@ -11,7 +11,7 @@ use std::{ffi::OsString, path::PathBuf}; | |||
11 | 11 | ||
12 | use lsp_types::ClientCapabilities; | 12 | use lsp_types::ClientCapabilities; |
13 | use ra_flycheck::FlycheckConfig; | 13 | use ra_flycheck::FlycheckConfig; |
14 | use ra_ide::{AssistConfig, CompletionConfig, InlayHintsConfig}; | 14 | use ra_ide::{AssistConfig, CompletionConfig, HoverConfig, InlayHintsConfig}; |
15 | use ra_project_model::{CargoConfig, JsonProject, ProjectManifest}; | 15 | use ra_project_model::{CargoConfig, JsonProject, ProjectManifest}; |
16 | use serde::Deserialize; | 16 | use serde::Deserialize; |
17 | 17 | ||
@@ -34,6 +34,7 @@ pub struct Config { | |||
34 | pub assist: AssistConfig, | 34 | pub assist: AssistConfig, |
35 | pub call_info_full: bool, | 35 | pub call_info_full: bool, |
36 | pub lens: LensConfig, | 36 | pub lens: LensConfig, |
37 | pub hover: HoverConfig, | ||
37 | 38 | ||
38 | pub with_sysroot: bool, | 39 | pub with_sysroot: bool, |
39 | pub linked_projects: Vec<LinkedProject>, | 40 | pub linked_projects: Vec<LinkedProject>, |
@@ -124,6 +125,7 @@ pub struct ClientCapsConfig { | |||
124 | pub work_done_progress: bool, | 125 | pub work_done_progress: bool, |
125 | pub code_action_group: bool, | 126 | pub code_action_group: bool, |
126 | pub resolve_code_action: bool, | 127 | pub resolve_code_action: bool, |
128 | pub hover_actions: bool, | ||
127 | } | 129 | } |
128 | 130 | ||
129 | impl Default for Config { | 131 | impl Default for Config { |
@@ -162,6 +164,7 @@ impl Default for Config { | |||
162 | assist: AssistConfig::default(), | 164 | assist: AssistConfig::default(), |
163 | call_info_full: true, | 165 | call_info_full: true, |
164 | lens: LensConfig::default(), | 166 | lens: LensConfig::default(), |
167 | hover: HoverConfig::default(), | ||
165 | linked_projects: Vec::new(), | 168 | linked_projects: Vec::new(), |
166 | } | 169 | } |
167 | } | 170 | } |
@@ -278,6 +281,14 @@ impl Config { | |||
278 | } | 281 | } |
279 | } | 282 | } |
280 | 283 | ||
284 | let mut use_hover_actions = false; | ||
285 | set(value, "/hoverActions/enable", &mut use_hover_actions); | ||
286 | if use_hover_actions { | ||
287 | set(value, "/hoverActions/implementations", &mut self.hover.implementations); | ||
288 | } else { | ||
289 | self.hover = HoverConfig::NO_ACTIONS; | ||
290 | } | ||
291 | |||
281 | log::info!("Config::update() = {:#?}", self); | 292 | log::info!("Config::update() = {:#?}", self); |
282 | 293 | ||
283 | fn get<'a, T: Deserialize<'a>>(value: &'a serde_json::Value, pointer: &str) -> Option<T> { | 294 | fn get<'a, T: Deserialize<'a>>(value: &'a serde_json::Value, pointer: &str) -> Option<T> { |
@@ -331,17 +342,15 @@ impl Config { | |||
331 | 342 | ||
332 | self.assist.allow_snippets(false); | 343 | self.assist.allow_snippets(false); |
333 | if let Some(experimental) = &caps.experimental { | 344 | if let Some(experimental) = &caps.experimental { |
334 | let snippet_text_edit = | 345 | let get_bool = |
335 | experimental.get("snippetTextEdit").and_then(|it| it.as_bool()) == Some(true); | 346 | |index: &str| experimental.get(index).and_then(|it| it.as_bool()) == Some(true); |
336 | self.assist.allow_snippets(snippet_text_edit); | ||
337 | 347 | ||
338 | let code_action_group = | 348 | let snippet_text_edit = get_bool("snippetTextEdit"); |
339 | experimental.get("codeActionGroup").and_then(|it| it.as_bool()) == Some(true); | 349 | self.assist.allow_snippets(snippet_text_edit); |
340 | self.client_caps.code_action_group = code_action_group; | ||
341 | 350 | ||
342 | let resolve_code_action = | 351 | self.client_caps.code_action_group = get_bool("codeActionGroup"); |
343 | experimental.get("resolveCodeAction").and_then(|it| it.as_bool()) == Some(true); | 352 | self.client_caps.resolve_code_action = get_bool("resolveCodeAction"); |
344 | self.client_caps.resolve_code_action = resolve_code_action; | 353 | self.client_caps.hover_actions = get_bool("hoverActions"); |
345 | } | 354 | } |
346 | } | 355 | } |
347 | } | 356 | } |
diff --git a/crates/rust-analyzer/src/lsp_ext.rs b/crates/rust-analyzer/src/lsp_ext.rs index 3b957534d..1371f6cb4 100644 --- a/crates/rust-analyzer/src/lsp_ext.rs +++ b/crates/rust-analyzer/src/lsp_ext.rs | |||
@@ -260,3 +260,35 @@ pub struct SnippetTextEdit { | |||
260 | #[serde(skip_serializing_if = "Option::is_none")] | 260 | #[serde(skip_serializing_if = "Option::is_none")] |
261 | pub insert_text_format: Option<lsp_types::InsertTextFormat>, | 261 | pub insert_text_format: Option<lsp_types::InsertTextFormat>, |
262 | } | 262 | } |
263 | |||
264 | pub enum HoverRequest {} | ||
265 | |||
266 | impl Request for HoverRequest { | ||
267 | type Params = lsp_types::HoverParams; | ||
268 | type Result = Option<Hover>; | ||
269 | const METHOD: &'static str = "textDocument/hover"; | ||
270 | } | ||
271 | |||
272 | #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] | ||
273 | pub struct Hover { | ||
274 | #[serde(flatten)] | ||
275 | pub hover: lsp_types::Hover, | ||
276 | #[serde(skip_serializing_if = "Vec::is_empty")] | ||
277 | pub actions: Vec<CommandLinkGroup>, | ||
278 | } | ||
279 | |||
280 | #[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)] | ||
281 | pub struct CommandLinkGroup { | ||
282 | #[serde(skip_serializing_if = "Option::is_none")] | ||
283 | pub title: Option<String>, | ||
284 | pub commands: Vec<CommandLink>, | ||
285 | } | ||
286 | |||
287 | // LSP v3.15 Command does not have a `tooltip` field, vscode supports one. | ||
288 | #[derive(Debug, PartialEq, Clone, Default, Deserialize, Serialize)] | ||
289 | pub struct CommandLink { | ||
290 | #[serde(flatten)] | ||
291 | pub command: lsp_types::Command, | ||
292 | #[serde(skip_serializing_if = "Option::is_none")] | ||
293 | pub tooltip: Option<String>, | ||
294 | } | ||
diff --git a/crates/rust-analyzer/src/main_loop.rs b/crates/rust-analyzer/src/main_loop.rs index e60337b8e..752dbf145 100644 --- a/crates/rust-analyzer/src/main_loop.rs +++ b/crates/rust-analyzer/src/main_loop.rs | |||
@@ -510,6 +510,7 @@ fn on_request( | |||
510 | .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)? | 510 | .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)? |
511 | .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)? | 511 | .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)? |
512 | .on::<lsp_ext::ResolveCodeActionRequest>(handlers::handle_resolve_code_action)? | 512 | .on::<lsp_ext::ResolveCodeActionRequest>(handlers::handle_resolve_code_action)? |
513 | .on::<lsp_ext::HoverRequest>(handlers::handle_hover)? | ||
513 | .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)? | 514 | .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)? |
514 | .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)? | 515 | .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)? |
515 | .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)? | 516 | .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)? |
@@ -521,7 +522,6 @@ fn on_request( | |||
521 | .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)? | 522 | .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)? |
522 | .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)? | 523 | .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)? |
523 | .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)? | 524 | .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)? |
524 | .on::<lsp_types::request::HoverRequest>(handlers::handle_hover)? | ||
525 | .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)? | 525 | .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)? |
526 | .on::<lsp_types::request::Rename>(handlers::handle_rename)? | 526 | .on::<lsp_types::request::Rename>(handlers::handle_rename)? |
527 | .on::<lsp_types::request::References>(handlers::handle_references)? | 527 | .on::<lsp_types::request::References>(handlers::handle_references)? |
diff --git a/crates/rust-analyzer/src/main_loop/handlers.rs b/crates/rust-analyzer/src/main_loop/handlers.rs index 6acf80c58..3ff779702 100644 --- a/crates/rust-analyzer/src/main_loop/handlers.rs +++ b/crates/rust-analyzer/src/main_loop/handlers.rs | |||
@@ -12,13 +12,14 @@ use lsp_types::{ | |||
12 | CallHierarchyIncomingCall, CallHierarchyIncomingCallsParams, CallHierarchyItem, | 12 | CallHierarchyIncomingCall, CallHierarchyIncomingCallsParams, CallHierarchyItem, |
13 | CallHierarchyOutgoingCall, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, | 13 | CallHierarchyOutgoingCall, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams, |
14 | CodeLens, Command, CompletionItem, Diagnostic, DocumentFormattingParams, DocumentHighlight, | 14 | CodeLens, Command, CompletionItem, Diagnostic, DocumentFormattingParams, DocumentHighlight, |
15 | DocumentSymbol, FoldingRange, FoldingRangeParams, Hover, HoverContents, Location, | 15 | DocumentSymbol, FoldingRange, FoldingRangeParams, HoverContents, Location, MarkupContent, |
16 | MarkupContent, MarkupKind, Position, PrepareRenameResponse, Range, RenameParams, | 16 | MarkupKind, Position, PrepareRenameResponse, Range, RenameParams, SemanticTokensParams, |
17 | SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult, | 17 | SemanticTokensRangeParams, SemanticTokensRangeResult, SemanticTokensResult, SymbolInformation, |
18 | SemanticTokensResult, SymbolInformation, TextDocumentIdentifier, Url, WorkspaceEdit, | 18 | TextDocumentIdentifier, Url, WorkspaceEdit, |
19 | }; | 19 | }; |
20 | use ra_ide::{ | 20 | use ra_ide::{ |
21 | FileId, FilePosition, FileRange, Query, RangeInfo, RunnableKind, SearchScope, TextEdit, | 21 | FileId, FilePosition, FileRange, HoverAction, Query, RangeInfo, RunnableKind, SearchScope, |
22 | TextEdit, | ||
22 | }; | 23 | }; |
23 | use ra_prof::profile; | 24 | use ra_prof::profile; |
24 | use ra_project_model::TargetKind; | 25 | use ra_project_model::TargetKind; |
@@ -537,7 +538,7 @@ pub fn handle_signature_help( | |||
537 | pub fn handle_hover( | 538 | pub fn handle_hover( |
538 | snap: GlobalStateSnapshot, | 539 | snap: GlobalStateSnapshot, |
539 | params: lsp_types::HoverParams, | 540 | params: lsp_types::HoverParams, |
540 | ) -> Result<Option<Hover>> { | 541 | ) -> Result<Option<lsp_ext::Hover>> { |
541 | let _p = profile("handle_hover"); | 542 | let _p = profile("handle_hover"); |
542 | let position = from_proto::file_position(&snap, params.text_document_position_params)?; | 543 | let position = from_proto::file_position(&snap, params.text_document_position_params)?; |
543 | let info = match snap.analysis().hover(position)? { | 544 | let info = match snap.analysis().hover(position)? { |
@@ -546,14 +547,18 @@ pub fn handle_hover( | |||
546 | }; | 547 | }; |
547 | let line_index = snap.analysis.file_line_index(position.file_id)?; | 548 | let line_index = snap.analysis.file_line_index(position.file_id)?; |
548 | let range = to_proto::range(&line_index, info.range); | 549 | let range = to_proto::range(&line_index, info.range); |
549 | let res = Hover { | 550 | let hover = lsp_ext::Hover { |
550 | contents: HoverContents::Markup(MarkupContent { | 551 | hover: lsp_types::Hover { |
551 | kind: MarkupKind::Markdown, | 552 | contents: HoverContents::Markup(MarkupContent { |
552 | value: crate::markdown::format_docs(&info.info.to_markup()), | 553 | kind: MarkupKind::Markdown, |
553 | }), | 554 | value: crate::markdown::format_docs(&info.info.to_markup()), |
554 | range: Some(range), | 555 | }), |
556 | range: Some(range), | ||
557 | }, | ||
558 | actions: prepare_hover_actions(&snap, info.info.actions()), | ||
555 | }; | 559 | }; |
556 | Ok(Some(res)) | 560 | |
561 | Ok(Some(hover)) | ||
557 | } | 562 | } |
558 | 563 | ||
559 | pub fn handle_prepare_rename( | 564 | pub fn handle_prepare_rename( |
@@ -924,24 +929,13 @@ pub fn handle_code_lens_resolve( | |||
924 | _ => vec![], | 929 | _ => vec![], |
925 | }; | 930 | }; |
926 | 931 | ||
927 | let title = if locations.len() == 1 { | 932 | let title = implementation_title(locations.len()); |
928 | "1 implementation".into() | 933 | let cmd = show_references_command( |
929 | } else { | ||
930 | format!("{} implementations", locations.len()) | ||
931 | }; | ||
932 | |||
933 | // We cannot use the 'editor.action.showReferences' command directly | ||
934 | // because that command requires vscode types which we convert in the handler | ||
935 | // on the client side. | ||
936 | let cmd = Command { | ||
937 | title, | 934 | title, |
938 | command: "rust-analyzer.showReferences".into(), | 935 | &lens_params.text_document_position_params.text_document.uri, |
939 | arguments: Some(vec![ | 936 | code_lens.range.start, |
940 | to_value(&lens_params.text_document_position_params.text_document.uri).unwrap(), | 937 | locations, |
941 | to_value(code_lens.range.start).unwrap(), | 938 | ); |
942 | to_value(locations).unwrap(), | ||
943 | ]), | ||
944 | }; | ||
945 | Ok(CodeLens { range: code_lens.range, command: Some(cmd), data: None }) | 939 | Ok(CodeLens { range: code_lens.range, command: Some(cmd), data: None }) |
946 | } | 940 | } |
947 | None => Ok(CodeLens { | 941 | None => Ok(CodeLens { |
@@ -1145,3 +1139,78 @@ pub fn handle_semantic_tokens_range( | |||
1145 | let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights); | 1139 | let semantic_tokens = to_proto::semantic_tokens(&text, &line_index, highlights); |
1146 | Ok(Some(semantic_tokens.into())) | 1140 | Ok(Some(semantic_tokens.into())) |
1147 | } | 1141 | } |
1142 | |||
1143 | fn implementation_title(count: usize) -> String { | ||
1144 | if count == 1 { | ||
1145 | "1 implementation".into() | ||
1146 | } else { | ||
1147 | format!("{} implementations", count) | ||
1148 | } | ||
1149 | } | ||
1150 | |||
1151 | fn show_references_command( | ||
1152 | title: String, | ||
1153 | uri: &lsp_types::Url, | ||
1154 | position: lsp_types::Position, | ||
1155 | locations: Vec<lsp_types::Location>, | ||
1156 | ) -> Command { | ||
1157 | // We cannot use the 'editor.action.showReferences' command directly | ||
1158 | // because that command requires vscode types which we convert in the handler | ||
1159 | // on the client side. | ||
1160 | |||
1161 | Command { | ||
1162 | title, | ||
1163 | command: "rust-analyzer.showReferences".into(), | ||
1164 | arguments: Some(vec![ | ||
1165 | to_value(uri).unwrap(), | ||
1166 | to_value(position).unwrap(), | ||
1167 | to_value(locations).unwrap(), | ||
1168 | ]), | ||
1169 | } | ||
1170 | } | ||
1171 | |||
1172 | fn to_command_link(command: Command, tooltip: String) -> lsp_ext::CommandLink { | ||
1173 | lsp_ext::CommandLink { tooltip: Some(tooltip), command } | ||
1174 | } | ||
1175 | |||
1176 | fn show_impl_command_link( | ||
1177 | snap: &GlobalStateSnapshot, | ||
1178 | position: &FilePosition, | ||
1179 | ) -> Option<lsp_ext::CommandLinkGroup> { | ||
1180 | if snap.config.hover.implementations { | ||
1181 | if let Some(nav_data) = snap.analysis().goto_implementation(*position).unwrap_or(None) { | ||
1182 | let uri = to_proto::url(snap, position.file_id).ok()?; | ||
1183 | let line_index = snap.analysis().file_line_index(position.file_id).ok()?; | ||
1184 | let position = to_proto::position(&line_index, position.offset); | ||
1185 | let locations: Vec<_> = nav_data | ||
1186 | .info | ||
1187 | .iter() | ||
1188 | .filter_map(|it| to_proto::location(snap, it.file_range()).ok()) | ||
1189 | .collect(); | ||
1190 | let title = implementation_title(locations.len()); | ||
1191 | let command = show_references_command(title, &uri, position, locations); | ||
1192 | |||
1193 | return Some(lsp_ext::CommandLinkGroup { | ||
1194 | commands: vec![to_command_link(command, "Go to implementations".into())], | ||
1195 | ..Default::default() | ||
1196 | }); | ||
1197 | } | ||
1198 | } | ||
1199 | None | ||
1200 | } | ||
1201 | |||
1202 | fn prepare_hover_actions( | ||
1203 | snap: &GlobalStateSnapshot, | ||
1204 | actions: &[HoverAction], | ||
1205 | ) -> Vec<lsp_ext::CommandLinkGroup> { | ||
1206 | if snap.config.hover.none() || !snap.config.client_caps.hover_actions { | ||
1207 | return Vec::new(); | ||
1208 | } | ||
1209 | |||
1210 | actions | ||
1211 | .iter() | ||
1212 | .filter_map(|it| match it { | ||
1213 | HoverAction::Implementaion(position) => show_impl_command_link(snap, position), | ||
1214 | }) | ||
1215 | .collect() | ||
1216 | } | ||