]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/navigation_target.rs
Simplify
[rust.git] / crates / ide / src / 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     SymbolKind,
13 };
14 use ide_db::{defs::Definition, RootDatabase};
15 use syntax::{
16     ast::{self, HasName},
17     match_ast, AstNode, SmolStr, TextRange,
18 };
19
20 use crate::FileSymbol;
21
22 /// `NavigationTarget` represents an 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 within 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.
41     ///
42     /// Clients should place the cursor on this range when navigating to this target.
43     pub focus_range: Option<TextRange>,
44     pub name: SmolStr,
45     pub kind: Option<SymbolKind>,
46     pub container_name: Option<SmolStr>,
47     pub description: Option<String>,
48     pub docs: Option<Documentation>,
49 }
50
51 impl fmt::Debug for NavigationTarget {
52     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53         let mut f = f.debug_struct("NavigationTarget");
54         macro_rules! opt {
55             ($($name:ident)*) => {$(
56                 if let Some(it) = &self.$name {
57                     f.field(stringify!($name), it);
58                 }
59             )*}
60         }
61         f.field("file_id", &self.file_id).field("full_range", &self.full_range);
62         opt!(focus_range);
63         f.field("name", &self.name);
64         opt!(kind container_name description docs);
65         f.finish()
66     }
67 }
68
69 pub(crate) trait ToNav {
70     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget;
71 }
72
73 pub(crate) trait TryToNav {
74     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget>;
75 }
76
77 impl<T: TryToNav, U: TryToNav> TryToNav for Either<T, U> {
78     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
79         match self {
80             Either::Left(it) => it.try_to_nav(db),
81             Either::Right(it) => it.try_to_nav(db),
82         }
83     }
84 }
85
86 impl NavigationTarget {
87     pub fn focus_or_full_range(&self) -> TextRange {
88         self.focus_range.unwrap_or(self.full_range)
89     }
90
91     pub(crate) fn from_module_to_decl(db: &RootDatabase, module: hir::Module) -> NavigationTarget {
92         let name = module.name(db).map(|it| it.to_smol_str()).unwrap_or_default();
93         if let Some(src @ InFile { value, .. }) = &module.declaration_source(db) {
94             let FileRange { file_id, range: full_range } = src.syntax().original_file_range(db);
95             let focus_range = value
96                 .name()
97                 .and_then(|name| src.with_value(name.syntax()).original_file_range_opt(db))
98                 .map(|it| it.range);
99             let mut res = NavigationTarget::from_syntax(
100                 file_id,
101                 name,
102                 focus_range,
103                 full_range,
104                 SymbolKind::Module,
105             );
106             res.docs = module.attrs(db).docs();
107             res.description = Some(module.display(db).to_string());
108             return res;
109         }
110         module.to_nav(db)
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::HasName>,
135         kind: SymbolKind,
136     ) -> NavigationTarget {
137         let name = node.value.name().map(|it| it.text().into()).unwrap_or_else(|| "_".into());
138         let focus_range = node
139             .value
140             .name()
141             .and_then(|it| node.with_value(it.syntax()).original_file_range_opt(db))
142             .map(|it| it.range);
143         let FileRange { file_id, range } = node.map(|it| it.syntax()).original_file_range(db);
144
145         NavigationTarget::from_syntax(file_id, name, focus_range, range, kind)
146     }
147
148     fn from_syntax(
149         file_id: FileId,
150         name: SmolStr,
151         focus_range: Option<TextRange>,
152         full_range: TextRange,
153         kind: SymbolKind,
154     ) -> NavigationTarget {
155         NavigationTarget {
156             file_id,
157             name,
158             kind: Some(kind),
159             full_range,
160             focus_range,
161             container_name: None,
162             description: None,
163             docs: None,
164         }
165     }
166 }
167
168 impl TryToNav for FileSymbol {
169     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
170         let full_range = self.loc.original_range(db)?;
171         let name_range = self.loc.original_name_range(db)?;
172
173         Some(NavigationTarget {
174             file_id: full_range.file_id,
175             name: self.name.clone(),
176             kind: Some(self.kind.into()),
177             full_range: full_range.range,
178             focus_range: Some(name_range.range),
179             container_name: self.container_name.clone(),
180             description: description_from_symbol(db, self),
181             docs: None,
182         })
183     }
184 }
185
186 impl TryToNav for Definition {
187     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
188         match self {
189             Definition::Local(it) => Some(it.to_nav(db)),
190             Definition::Label(it) => Some(it.to_nav(db)),
191             Definition::Module(it) => Some(it.to_nav(db)),
192             Definition::Macro(it) => it.try_to_nav(db),
193             Definition::Field(it) => it.try_to_nav(db),
194             Definition::SelfType(it) => it.try_to_nav(db),
195             Definition::GenericParam(it) => it.try_to_nav(db),
196             Definition::Function(it) => it.try_to_nav(db),
197             Definition::Adt(it) => it.try_to_nav(db),
198             Definition::Variant(it) => it.try_to_nav(db),
199             Definition::Const(it) => it.try_to_nav(db),
200             Definition::Static(it) => it.try_to_nav(db),
201             Definition::Trait(it) => it.try_to_nav(db),
202             Definition::TypeAlias(it) => it.try_to_nav(db),
203             Definition::BuiltinType(_) => None,
204             Definition::ToolModule(_) => None,
205             Definition::BuiltinAttr(_) => None,
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 InFile { file_id, value } = self.definition_source(db);
278
279         let name = self.name(db).map(|it| it.to_smol_str()).unwrap_or_default();
280         let (syntax, focus) = match &value {
281             ModuleSource::SourceFile(node) => (node.syntax(), None),
282             ModuleSource::Module(node) => (
283                 node.syntax(),
284                 node.name()
285                     .and_then(|it| InFile::new(file_id, it.syntax()).original_file_range_opt(db))
286                     .map(|it| it.range),
287             ),
288             ModuleSource::BlockExpr(node) => (node.syntax(), None),
289         };
290         let FileRange { file_id, range: full_range } =
291             InFile::new(file_id, syntax).original_file_range(db);
292         NavigationTarget::from_syntax(file_id, name, focus, full_range, SymbolKind::Module)
293     }
294 }
295
296 impl TryToNav for hir::Impl {
297     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
298         let InFile { file_id, value } = self.source(db)?;
299         let derive_attr = self.is_builtin_derive(db);
300
301         let range = |syntax: &_| InFile::new(file_id, syntax).original_file_range(db);
302         let focus_range = if derive_attr.is_some() {
303             None
304         } else {
305             value
306                 .self_ty()
307                 .and_then(|ty| InFile::new(file_id, ty.syntax()).original_file_range_opt(db))
308                 .map(|it| it.range)
309         };
310         let FileRange { file_id, range: full_range } = match &derive_attr {
311             Some(InFile { value, .. }) => range(value.syntax()),
312             None => range(value.syntax()),
313         };
314
315         Some(NavigationTarget::from_syntax(
316             file_id,
317             "impl".into(),
318             focus_range,
319             full_range,
320             SymbolKind::Impl,
321         ))
322     }
323 }
324
325 impl TryToNav for hir::Field {
326     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
327         let src = self.source(db)?;
328
329         let field_source = match &src.value {
330             FieldSource::Named(it) => {
331                 let mut res =
332                     NavigationTarget::from_named(db, src.with_value(it), SymbolKind::Field);
333                 res.docs = self.docs(db);
334                 res.description = Some(self.display(db).to_string());
335                 res
336             }
337             FieldSource::Pos(it) => {
338                 let FileRange { file_id, range } =
339                     src.with_value(it.syntax()).original_file_range(db);
340                 NavigationTarget::from_syntax(file_id, "".into(), None, range, SymbolKind::Field)
341             }
342         };
343         Some(field_source)
344     }
345 }
346
347 impl TryToNav for hir::MacroDef {
348     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
349         let src = self.source(db)?;
350         let name_owner: &dyn ast::HasName = match &src.value {
351             Either::Left(it) => it,
352             Either::Right(it) => it,
353         };
354         tracing::debug!("nav target {:#?}", name_owner.syntax());
355         let mut res = NavigationTarget::from_named(
356             db,
357             src.as_ref().with_value(name_owner),
358             self.kind().into(),
359         );
360         res.docs = self.docs(db);
361         Some(res)
362     }
363 }
364
365 impl TryToNav for hir::Adt {
366     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
367         match self {
368             hir::Adt::Struct(it) => it.try_to_nav(db),
369             hir::Adt::Union(it) => it.try_to_nav(db),
370             hir::Adt::Enum(it) => it.try_to_nav(db),
371         }
372     }
373 }
374
375 impl TryToNav for hir::AssocItem {
376     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
377         match self {
378             AssocItem::Function(it) => it.try_to_nav(db),
379             AssocItem::Const(it) => it.try_to_nav(db),
380             AssocItem::TypeAlias(it) => it.try_to_nav(db),
381         }
382     }
383 }
384
385 impl TryToNav for hir::GenericParam {
386     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
387         match self {
388             hir::GenericParam::TypeParam(it) => it.try_to_nav(db),
389             hir::GenericParam::ConstParam(it) => it.try_to_nav(db),
390             hir::GenericParam::LifetimeParam(it) => it.try_to_nav(db),
391         }
392     }
393 }
394
395 impl ToNav for hir::Local {
396     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
397         let InFile { file_id, value } = self.source(db);
398         let (node, name) = match &value {
399             Either::Left(bind_pat) => (bind_pat.syntax(), bind_pat.name()),
400             Either::Right(it) => (it.syntax(), it.name()),
401         };
402         let focus_range = name
403             .and_then(|it| InFile::new(file_id, it.syntax()).original_file_range_opt(db))
404             .map(|it| it.range);
405         let FileRange { file_id, range: full_range } =
406             InFile::new(file_id, node).original_file_range(db);
407
408         let name = match self.name(db) {
409             Some(it) => it.to_smol_str(),
410             None => "".into(),
411         };
412         let kind = if self.is_self(db) {
413             SymbolKind::SelfParam
414         } else if self.is_param(db) {
415             SymbolKind::ValueParam
416         } else {
417             SymbolKind::Local
418         };
419         NavigationTarget {
420             file_id,
421             name,
422             kind: Some(kind),
423             full_range,
424             focus_range,
425             container_name: None,
426             description: None,
427             docs: None,
428         }
429     }
430 }
431
432 impl ToNav for hir::Label {
433     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
434         let InFile { file_id, value } = self.source(db);
435         let name = self.name(db).to_smol_str();
436
437         let range = |syntax: &_| InFile::new(file_id, syntax).original_file_range(db);
438         let FileRange { file_id, range: full_range } = range(value.syntax());
439         let focus_range = value.lifetime().map(|lt| range(lt.syntax()).range);
440
441         NavigationTarget {
442             file_id,
443             name,
444             kind: Some(SymbolKind::Label),
445             full_range,
446             focus_range,
447             container_name: None,
448             description: None,
449             docs: None,
450         }
451     }
452 }
453
454 impl TryToNav for hir::TypeParam {
455     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
456         let InFile { file_id, value } = self.source(db)?;
457         let name = self.name(db).to_smol_str();
458
459         let range = |syntax: &_| InFile::new(file_id, syntax).original_file_range(db);
460         let focus_range = |syntax: &_| InFile::new(file_id, syntax).original_file_range_opt(db);
461         let FileRange { file_id, range: full_range } = match &value {
462             Either::Left(type_param) => range(type_param.syntax()),
463             Either::Right(trait_) => trait_
464                 .name()
465                 .and_then(|name| focus_range(name.syntax()))
466                 .unwrap_or_else(|| range(trait_.syntax())),
467         };
468         let focus_range = value
469             .either(|it| it.name(), |it| it.name())
470             .and_then(|it| focus_range(it.syntax()))
471             .map(|it| it.range);
472         Some(NavigationTarget {
473             file_id,
474             name,
475             kind: Some(SymbolKind::TypeParam),
476             full_range,
477             focus_range,
478             container_name: None,
479             description: None,
480             docs: None,
481         })
482     }
483 }
484
485 impl TryToNav for hir::LifetimeParam {
486     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
487         let InFile { file_id, value } = self.source(db)?;
488         let name = self.name(db).to_smol_str();
489
490         let FileRange { file_id, range: full_range } =
491             InFile::new(file_id, value.syntax()).original_file_range(db);
492         Some(NavigationTarget {
493             file_id,
494             name,
495             kind: Some(SymbolKind::LifetimeParam),
496             full_range,
497             focus_range: Some(full_range),
498             container_name: None,
499             description: None,
500             docs: None,
501         })
502     }
503 }
504
505 impl TryToNav for hir::ConstParam {
506     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
507         let InFile { file_id, value } = self.source(db)?;
508         let name = self.name(db).to_smol_str();
509
510         let focus_range = value
511             .name()
512             .and_then(|it| InFile::new(file_id, it.syntax()).original_file_range_opt(db))
513             .map(|it| it.range);
514         let FileRange { file_id, range: full_range } =
515             InFile::new(file_id, value.syntax()).original_file_range(db);
516         Some(NavigationTarget {
517             file_id,
518             name,
519             kind: Some(SymbolKind::ConstParam),
520             full_range,
521             focus_range,
522             container_name: None,
523             description: None,
524             docs: None,
525         })
526     }
527 }
528
529 /// Get a description of a symbol.
530 ///
531 /// e.g. `struct Name`, `enum Name`, `fn Name`
532 pub(crate) fn description_from_symbol(db: &RootDatabase, symbol: &FileSymbol) -> Option<String> {
533     let sema = Semantics::new(db);
534     let node = symbol.loc.syntax(&sema)?;
535
536     match_ast! {
537         match node {
538             ast::Fn(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
539             ast::Struct(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
540             ast::Enum(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
541             ast::Trait(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
542             ast::Module(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
543             ast::TypeAlias(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
544             ast::Const(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
545             ast::Static(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
546             ast::RecordField(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
547             ast::Variant(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
548             ast::Union(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
549             _ => None,
550         }
551     }
552 }
553
554 #[cfg(test)]
555 mod tests {
556     use expect_test::expect;
557
558     use crate::{fixture, Query};
559
560     #[test]
561     fn test_nav_for_symbol() {
562         let (analysis, _) = fixture::file(
563             r#"
564 enum FooInner { }
565 fn foo() { enum FooInner { } }
566 "#,
567         );
568
569         let navs = analysis.symbol_search(Query::new("FooInner".to_string())).unwrap();
570         expect![[r#"
571             [
572                 NavigationTarget {
573                     file_id: FileId(
574                         0,
575                     ),
576                     full_range: 0..17,
577                     focus_range: 5..13,
578                     name: "FooInner",
579                     kind: Enum,
580                     description: "enum FooInner",
581                 },
582                 NavigationTarget {
583                     file_id: FileId(
584                         0,
585                     ),
586                     full_range: 29..46,
587                     focus_range: 34..42,
588                     name: "FooInner",
589                     kind: Enum,
590                     container_name: "foo",
591                     description: "enum FooInner",
592                 },
593             ]
594         "#]]
595         .assert_debug_eq(&navs);
596     }
597
598     #[test]
599     fn test_world_symbols_are_case_sensitive() {
600         let (analysis, _) = fixture::file(
601             r#"
602 fn foo() {}
603 struct Foo;
604 "#,
605         );
606
607         let navs = analysis.symbol_search(Query::new("foo".to_string())).unwrap();
608         assert_eq!(navs.len(), 2)
609     }
610 }