]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/display/navigation_target.rs
Merge #6958
[rust.git] / crates / ide / src / display / navigation_target.rs
1 //! FIXME: write short doc here
2
3 use std::fmt;
4
5 use either::Either;
6 use hir::{AssocItem, Documentation, FieldSource, HasAttrs, HasSource, InFile, ModuleSource};
7 use ide_db::{
8     base_db::{FileId, SourceDatabase},
9     symbol_index::FileSymbolKind,
10 };
11 use ide_db::{defs::Definition, RootDatabase};
12 use syntax::{
13     ast::{self, NameOwner},
14     match_ast, AstNode, SmolStr, TextRange,
15 };
16
17 use crate::FileSymbol;
18
19 use super::short_label::ShortLabel;
20
21 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
22 pub enum SymbolKind {
23     Module,
24     Impl,
25     Field,
26     TypeParam,
27     LifetimeParam,
28     ValueParam,
29     SelfParam,
30     Local,
31     Function,
32     Const,
33     Static,
34     Struct,
35     Enum,
36     Variant,
37     Union,
38     TypeAlias,
39     Trait,
40     Macro,
41 }
42
43 /// `NavigationTarget` represents and element in the editor's UI which you can
44 /// click on to navigate to a particular piece of code.
45 ///
46 /// Typically, a `NavigationTarget` corresponds to some element in the source
47 /// code, like a function or a struct, but this is not strictly required.
48 #[derive(Clone, PartialEq, Eq, Hash)]
49 pub struct NavigationTarget {
50     pub file_id: FileId,
51     /// Range which encompasses the whole element.
52     ///
53     /// Should include body, doc comments, attributes, etc.
54     ///
55     /// Clients should use this range to answer "is the cursor inside the
56     /// element?" question.
57     pub full_range: TextRange,
58     /// A "most interesting" range withing the `full_range`.
59     ///
60     /// Typically, `full_range` is the whole syntax node, including doc
61     /// comments, and `focus_range` is the range of the identifier. "Most
62     /// interesting" range within the full range, typically the range of
63     /// identifier.
64     ///
65     /// Clients should place the cursor on this range when navigating to this target.
66     pub focus_range: Option<TextRange>,
67     pub name: SmolStr,
68     pub kind: Option<SymbolKind>,
69     pub container_name: Option<SmolStr>,
70     pub description: Option<String>,
71     pub docs: Option<Documentation>,
72 }
73
74 impl fmt::Debug for NavigationTarget {
75     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76         let mut f = f.debug_struct("NavigationTarget");
77         macro_rules! opt {
78             ($($name:ident)*) => {$(
79                 if let Some(it) = &self.$name {
80                     f.field(stringify!($name), it);
81                 }
82             )*}
83         }
84         f.field("file_id", &self.file_id).field("full_range", &self.full_range);
85         opt!(focus_range);
86         f.field("name", &self.name);
87         opt!(kind container_name description docs);
88         f.finish()
89     }
90 }
91
92 pub(crate) trait ToNav {
93     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget;
94 }
95
96 pub(crate) trait TryToNav {
97     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget>;
98 }
99
100 impl NavigationTarget {
101     pub fn focus_or_full_range(&self) -> TextRange {
102         self.focus_range.unwrap_or(self.full_range)
103     }
104
105     pub(crate) fn from_module_to_decl(db: &RootDatabase, module: hir::Module) -> NavigationTarget {
106         let name = module.name(db).map(|it| it.to_string().into()).unwrap_or_default();
107         if let Some(src) = module.declaration_source(db) {
108             let node = src.as_ref().map(|it| it.syntax());
109             let frange = node.original_file_range(db);
110             let mut res = NavigationTarget::from_syntax(
111                 frange.file_id,
112                 name,
113                 None,
114                 frange.range,
115                 SymbolKind::Module,
116             );
117             res.docs = module.attrs(db).docs();
118             res.description = src.value.short_label();
119             return res;
120         }
121         module.to_nav(db)
122     }
123
124     #[cfg(test)]
125     pub(crate) fn assert_match(&self, expected: &str) {
126         let actual = self.debug_render();
127         test_utils::assert_eq_text!(expected.trim(), actual.trim(),);
128     }
129
130     #[cfg(test)]
131     pub(crate) fn debug_render(&self) -> String {
132         let mut buf = format!(
133             "{} {:?} {:?} {:?}",
134             self.name,
135             self.kind.unwrap(),
136             self.file_id,
137             self.full_range
138         );
139         if let Some(focus_range) = self.focus_range {
140             buf.push_str(&format!(" {:?}", focus_range))
141         }
142         if let Some(container_name) = &self.container_name {
143             buf.push_str(&format!(" {}", container_name))
144         }
145         buf
146     }
147
148     /// Allows `NavigationTarget` to be created from a `NameOwner`
149     pub(crate) fn from_named(
150         db: &RootDatabase,
151         node: InFile<&dyn ast::NameOwner>,
152         kind: SymbolKind,
153     ) -> NavigationTarget {
154         let name =
155             node.value.name().map(|it| it.text().clone()).unwrap_or_else(|| SmolStr::new("_"));
156         let focus_range =
157             node.value.name().map(|it| node.with_value(it.syntax()).original_file_range(db).range);
158         let frange = node.map(|it| it.syntax()).original_file_range(db);
159
160         NavigationTarget::from_syntax(frange.file_id, name, focus_range, frange.range, kind)
161     }
162
163     fn from_syntax(
164         file_id: FileId,
165         name: SmolStr,
166         focus_range: Option<TextRange>,
167         full_range: TextRange,
168         kind: SymbolKind,
169     ) -> NavigationTarget {
170         NavigationTarget {
171             file_id,
172             name,
173             kind: Some(kind),
174             full_range,
175             focus_range,
176             container_name: None,
177             description: None,
178             docs: None,
179         }
180     }
181 }
182
183 impl ToNav for FileSymbol {
184     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
185         NavigationTarget {
186             file_id: self.file_id,
187             name: self.name.clone(),
188             kind: Some(match self.kind {
189                 FileSymbolKind::Function => SymbolKind::Function,
190                 FileSymbolKind::Struct => SymbolKind::Struct,
191                 FileSymbolKind::Enum => SymbolKind::Enum,
192                 FileSymbolKind::Trait => SymbolKind::Trait,
193                 FileSymbolKind::Module => SymbolKind::Module,
194                 FileSymbolKind::TypeAlias => SymbolKind::TypeAlias,
195                 FileSymbolKind::Const => SymbolKind::Const,
196                 FileSymbolKind::Static => SymbolKind::Static,
197                 FileSymbolKind::Macro => SymbolKind::Macro,
198             }),
199             full_range: self.range,
200             focus_range: self.name_range,
201             container_name: self.container_name.clone(),
202             description: description_from_symbol(db, self),
203             docs: None,
204         }
205     }
206 }
207
208 impl TryToNav for Definition {
209     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
210         match self {
211             Definition::Macro(it) => {
212                 // FIXME: Currently proc-macro do not have ast-node,
213                 // such that it does not have source
214                 // more discussion: https://github.com/rust-analyzer/rust-analyzer/issues/6913
215                 if it.is_proc_macro() {
216                     return None;
217                 }
218                 Some(it.to_nav(db))
219             }
220             Definition::Field(it) => Some(it.to_nav(db)),
221             Definition::ModuleDef(it) => it.try_to_nav(db),
222             Definition::SelfType(it) => Some(it.to_nav(db)),
223             Definition::Local(it) => Some(it.to_nav(db)),
224             Definition::TypeParam(it) => Some(it.to_nav(db)),
225             Definition::LifetimeParam(it) => Some(it.to_nav(db)),
226         }
227     }
228 }
229
230 impl TryToNav for hir::ModuleDef {
231     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
232         let res = match self {
233             hir::ModuleDef::Module(it) => it.to_nav(db),
234             hir::ModuleDef::Function(it) => it.to_nav(db),
235             hir::ModuleDef::Adt(it) => it.to_nav(db),
236             hir::ModuleDef::Variant(it) => it.to_nav(db),
237             hir::ModuleDef::Const(it) => it.to_nav(db),
238             hir::ModuleDef::Static(it) => it.to_nav(db),
239             hir::ModuleDef::Trait(it) => it.to_nav(db),
240             hir::ModuleDef::TypeAlias(it) => it.to_nav(db),
241             hir::ModuleDef::BuiltinType(_) => return None,
242         };
243         Some(res)
244     }
245 }
246
247 pub(crate) trait ToNavFromAst {
248     const KIND: SymbolKind;
249 }
250 impl ToNavFromAst for hir::Function {
251     const KIND: SymbolKind = SymbolKind::Function;
252 }
253 impl ToNavFromAst for hir::Const {
254     const KIND: SymbolKind = SymbolKind::Const;
255 }
256 impl ToNavFromAst for hir::Static {
257     const KIND: SymbolKind = SymbolKind::Static;
258 }
259 impl ToNavFromAst for hir::Struct {
260     const KIND: SymbolKind = SymbolKind::Struct;
261 }
262 impl ToNavFromAst for hir::Enum {
263     const KIND: SymbolKind = SymbolKind::Enum;
264 }
265 impl ToNavFromAst for hir::Variant {
266     const KIND: SymbolKind = SymbolKind::Variant;
267 }
268 impl ToNavFromAst for hir::Union {
269     const KIND: SymbolKind = SymbolKind::Union;
270 }
271 impl ToNavFromAst for hir::TypeAlias {
272     const KIND: SymbolKind = SymbolKind::TypeAlias;
273 }
274 impl ToNavFromAst for hir::Trait {
275     const KIND: SymbolKind = SymbolKind::Trait;
276 }
277
278 impl<D> ToNav for D
279 where
280     D: HasSource + ToNavFromAst + Copy + HasAttrs,
281     D::Ast: ast::NameOwner + ShortLabel,
282 {
283     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
284         let src = self.source(db);
285         let mut res = NavigationTarget::from_named(
286             db,
287             src.as_ref().map(|it| it as &dyn ast::NameOwner),
288             D::KIND,
289         );
290         res.docs = self.docs(db);
291         res.description = src.value.short_label();
292         res
293     }
294 }
295
296 impl ToNav for hir::Module {
297     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
298         let src = self.definition_source(db);
299         let name = self.name(db).map(|it| it.to_string().into()).unwrap_or_default();
300         let (syntax, focus) = match &src.value {
301             ModuleSource::SourceFile(node) => (node.syntax(), None),
302             ModuleSource::Module(node) => {
303                 (node.syntax(), node.name().map(|it| it.syntax().text_range()))
304             }
305         };
306         let frange = src.with_value(syntax).original_file_range(db);
307         NavigationTarget::from_syntax(frange.file_id, name, focus, frange.range, SymbolKind::Module)
308     }
309 }
310
311 impl ToNav for hir::Impl {
312     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
313         let src = self.source(db);
314         let derive_attr = self.is_builtin_derive(db);
315         let frange = if let Some(item) = &derive_attr {
316             item.syntax().original_file_range(db)
317         } else {
318             src.as_ref().map(|it| it.syntax()).original_file_range(db)
319         };
320         let focus_range = if derive_attr.is_some() {
321             None
322         } else {
323             src.value.self_ty().map(|ty| src.with_value(ty.syntax()).original_file_range(db).range)
324         };
325
326         NavigationTarget::from_syntax(
327             frange.file_id,
328             "impl".into(),
329             focus_range,
330             frange.range,
331             SymbolKind::Impl,
332         )
333     }
334 }
335
336 impl ToNav for hir::Field {
337     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
338         let src = self.source(db);
339
340         match &src.value {
341             FieldSource::Named(it) => {
342                 let mut res =
343                     NavigationTarget::from_named(db, src.with_value(it), SymbolKind::Field);
344                 res.docs = self.docs(db);
345                 res.description = it.short_label();
346                 res
347             }
348             FieldSource::Pos(it) => {
349                 let frange = src.with_value(it.syntax()).original_file_range(db);
350                 NavigationTarget::from_syntax(
351                     frange.file_id,
352                     "".into(),
353                     None,
354                     frange.range,
355                     SymbolKind::Field,
356                 )
357             }
358         }
359     }
360 }
361
362 impl ToNav for hir::MacroDef {
363     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
364         let src = self.source(db);
365         log::debug!("nav target {:#?}", src.value.syntax());
366         let mut res = NavigationTarget::from_named(
367             db,
368             src.as_ref().map(|it| it as &dyn ast::NameOwner),
369             SymbolKind::Macro,
370         );
371         res.docs = self.docs(db);
372         res
373     }
374 }
375
376 impl ToNav for hir::Adt {
377     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
378         match self {
379             hir::Adt::Struct(it) => it.to_nav(db),
380             hir::Adt::Union(it) => it.to_nav(db),
381             hir::Adt::Enum(it) => it.to_nav(db),
382         }
383     }
384 }
385
386 impl ToNav for hir::AssocItem {
387     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
388         match self {
389             AssocItem::Function(it) => it.to_nav(db),
390             AssocItem::Const(it) => it.to_nav(db),
391             AssocItem::TypeAlias(it) => it.to_nav(db),
392         }
393     }
394 }
395
396 impl ToNav for hir::Local {
397     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
398         let src = self.source(db);
399         let node = match &src.value {
400             Either::Left(bind_pat) => {
401                 bind_pat.name().map_or_else(|| bind_pat.syntax().clone(), |it| it.syntax().clone())
402             }
403             Either::Right(it) => it.syntax().clone(),
404         };
405         let full_range = src.with_value(&node).original_file_range(db);
406         let name = match self.name(db) {
407             Some(it) => it.to_string().into(),
408             None => "".into(),
409         };
410         let kind = if self.is_param(db) { SymbolKind::ValueParam } else { SymbolKind::Local };
411         NavigationTarget {
412             file_id: full_range.file_id,
413             name,
414             kind: Some(kind),
415             full_range: full_range.range,
416             focus_range: None,
417             container_name: None,
418             description: None,
419             docs: None,
420         }
421     }
422 }
423
424 impl ToNav for hir::TypeParam {
425     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
426         let src = self.source(db);
427         let full_range = match &src.value {
428             Either::Left(it) => it.syntax().text_range(),
429             Either::Right(it) => it.syntax().text_range(),
430         };
431         let focus_range = match &src.value {
432             Either::Left(_) => None,
433             Either::Right(it) => it.name().map(|it| it.syntax().text_range()),
434         };
435         NavigationTarget {
436             file_id: src.file_id.original_file(db),
437             name: self.name(db).to_string().into(),
438             kind: Some(SymbolKind::TypeParam),
439             full_range,
440             focus_range,
441             container_name: None,
442             description: None,
443             docs: None,
444         }
445     }
446 }
447
448 impl ToNav for hir::LifetimeParam {
449     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
450         let src = self.source(db);
451         let full_range = src.value.syntax().text_range();
452         NavigationTarget {
453             file_id: src.file_id.original_file(db),
454             name: self.name(db).to_string().into(),
455             kind: Some(SymbolKind::LifetimeParam),
456             full_range,
457             focus_range: Some(full_range),
458             container_name: None,
459             description: None,
460             docs: None,
461         }
462     }
463 }
464
465 /// Get a description of a symbol.
466 ///
467 /// e.g. `struct Name`, `enum Name`, `fn Name`
468 pub(crate) fn description_from_symbol(db: &RootDatabase, symbol: &FileSymbol) -> Option<String> {
469     let parse = db.parse(symbol.file_id);
470     let node = symbol.ptr.to_node(parse.tree().syntax());
471
472     match_ast! {
473         match node {
474             ast::Fn(it) => it.short_label(),
475             ast::Struct(it) => it.short_label(),
476             ast::Enum(it) => it.short_label(),
477             ast::Trait(it) => it.short_label(),
478             ast::Module(it) => it.short_label(),
479             ast::TypeAlias(it) => it.short_label(),
480             ast::Const(it) => it.short_label(),
481             ast::Static(it) => it.short_label(),
482             ast::RecordField(it) => it.short_label(),
483             ast::Variant(it) => it.short_label(),
484             _ => None,
485         }
486     }
487 }
488
489 #[cfg(test)]
490 mod tests {
491     use expect_test::expect;
492
493     use crate::{fixture, Query};
494
495     #[test]
496     fn test_nav_for_symbol() {
497         let (analysis, _) = fixture::file(
498             r#"
499 enum FooInner { }
500 fn foo() { enum FooInner { } }
501 "#,
502         );
503
504         let navs = analysis.symbol_search(Query::new("FooInner".to_string())).unwrap();
505         expect![[r#"
506             [
507                 NavigationTarget {
508                     file_id: FileId(
509                         0,
510                     ),
511                     full_range: 0..17,
512                     focus_range: 5..13,
513                     name: "FooInner",
514                     kind: Enum,
515                     description: "enum FooInner",
516                 },
517                 NavigationTarget {
518                     file_id: FileId(
519                         0,
520                     ),
521                     full_range: 29..46,
522                     focus_range: 34..42,
523                     name: "FooInner",
524                     kind: Enum,
525                     container_name: "foo",
526                     description: "enum FooInner",
527                 },
528             ]
529         "#]]
530         .assert_debug_eq(&navs);
531     }
532
533     #[test]
534     fn test_world_symbols_are_case_sensitive() {
535         let (analysis, _) = fixture::file(
536             r#"
537 fn foo() {}
538 struct Foo;
539 "#,
540         );
541
542         let navs = analysis.symbol_search(Query::new("foo".to_string())).unwrap();
543         assert_eq!(navs.len(), 2)
544     }
545 }