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