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