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