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