]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/ide/src/navigation_target.rs
Rollup merge of #100228 - luqmana:suggestion-ice, r=estebank
[rust.git] / src / tools / rust-analyzer / 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 stdx::never;
16 use syntax::{
17     ast::{self, HasName},
18     match_ast, AstNode, SmolStr, SyntaxNode, TextRange,
19 };
20
21 /// `NavigationTarget` represents an element in the editor's UI which you can
22 /// click on to navigate to a particular piece of code.
23 ///
24 /// Typically, a `NavigationTarget` corresponds to some element in the source
25 /// code, like a function or a struct, but this is not strictly required.
26 #[derive(Clone, PartialEq, Eq, Hash)]
27 pub struct NavigationTarget {
28     pub file_id: FileId,
29     /// Range which encompasses the whole element.
30     ///
31     /// Should include body, doc comments, attributes, etc.
32     ///
33     /// Clients should use this range to answer "is the cursor inside the
34     /// element?" question.
35     pub full_range: TextRange,
36     /// A "most interesting" range within the `full_range`.
37     ///
38     /// Typically, `full_range` is the whole syntax node, including doc
39     /// comments, and `focus_range` is the range of the identifier.
40     ///
41     /// Clients should place the cursor on this range when navigating to this target.
42     pub focus_range: Option<TextRange>,
43     pub name: SmolStr,
44     pub kind: Option<SymbolKind>,
45     pub container_name: Option<SmolStr>,
46     pub description: Option<String>,
47     pub docs: Option<Documentation>,
48 }
49
50 impl fmt::Debug for NavigationTarget {
51     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52         let mut f = f.debug_struct("NavigationTarget");
53         macro_rules! opt {
54             ($($name:ident)*) => {$(
55                 if let Some(it) = &self.$name {
56                     f.field(stringify!($name), it);
57                 }
58             )*}
59         }
60         f.field("file_id", &self.file_id).field("full_range", &self.full_range);
61         opt!(focus_range);
62         f.field("name", &self.name);
63         opt!(kind container_name description docs);
64         f.finish()
65     }
66 }
67
68 pub(crate) trait ToNav {
69     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget;
70 }
71
72 pub(crate) trait TryToNav {
73     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget>;
74 }
75
76 impl<T: TryToNav, U: TryToNav> TryToNav for Either<T, U> {
77     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
78         match self {
79             Either::Left(it) => it.try_to_nav(db),
80             Either::Right(it) => it.try_to_nav(db),
81         }
82     }
83 }
84
85 impl NavigationTarget {
86     pub fn focus_or_full_range(&self) -> TextRange {
87         self.focus_range.unwrap_or(self.full_range)
88     }
89
90     pub(crate) fn from_module_to_decl(db: &RootDatabase, module: hir::Module) -> NavigationTarget {
91         let name = module.name(db).map(|it| it.to_smol_str()).unwrap_or_default();
92         if let Some(src @ InFile { value, .. }) = &module.declaration_source(db) {
93             let FileRange { file_id, range: full_range } = src.syntax().original_file_range(db);
94             let focus_range =
95                 value.name().and_then(|it| orig_focus_range(db, src.file_id, it.syntax()));
96             let mut res = NavigationTarget::from_syntax(
97                 file_id,
98                 name,
99                 focus_range,
100                 full_range,
101                 SymbolKind::Module,
102             );
103             res.docs = module.attrs(db).docs();
104             res.description = Some(module.display(db).to_string());
105             return res;
106         }
107         module.to_nav(db)
108     }
109
110     #[cfg(test)]
111     pub(crate) fn debug_render(&self) -> String {
112         let mut buf = format!(
113             "{} {:?} {:?} {:?}",
114             self.name,
115             self.kind.unwrap(),
116             self.file_id,
117             self.full_range
118         );
119         if let Some(focus_range) = self.focus_range {
120             buf.push_str(&format!(" {:?}", focus_range))
121         }
122         if let Some(container_name) = &self.container_name {
123             buf.push_str(&format!(" {}", container_name))
124         }
125         buf
126     }
127
128     /// Allows `NavigationTarget` to be created from a `NameOwner`
129     pub(crate) fn from_named(
130         db: &RootDatabase,
131         node @ InFile { file_id, value }: InFile<&dyn ast::HasName>,
132         kind: SymbolKind,
133     ) -> NavigationTarget {
134         let name = value.name().map(|it| it.text().into()).unwrap_or_else(|| "_".into());
135         let focus_range = value.name().and_then(|it| orig_focus_range(db, file_id, it.syntax()));
136         let FileRange { file_id, range } = node.map(|it| it.syntax()).original_file_range(db);
137
138         NavigationTarget::from_syntax(file_id, name, focus_range, 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 TryToNav for FileSymbol {
162     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
163         let full_range = self.loc.original_range(db)?;
164         let name_range = self.loc.original_name_range(db)?;
165
166         Some(NavigationTarget {
167             file_id: full_range.file_id,
168             name: self.name.clone(),
169             kind: Some(self.kind.into()),
170             full_range: full_range.range,
171             focus_range: Some(name_range.range),
172             container_name: self.container_name.clone(),
173             description: description_from_symbol(db, self),
174             docs: None,
175         })
176     }
177 }
178
179 impl TryToNav for Definition {
180     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
181         match self {
182             Definition::Local(it) => Some(it.to_nav(db)),
183             Definition::Label(it) => Some(it.to_nav(db)),
184             Definition::Module(it) => Some(it.to_nav(db)),
185             Definition::Macro(it) => it.try_to_nav(db),
186             Definition::Field(it) => it.try_to_nav(db),
187             Definition::SelfType(it) => it.try_to_nav(db),
188             Definition::GenericParam(it) => it.try_to_nav(db),
189             Definition::Function(it) => it.try_to_nav(db),
190             Definition::Adt(it) => it.try_to_nav(db),
191             Definition::Variant(it) => it.try_to_nav(db),
192             Definition::Const(it) => it.try_to_nav(db),
193             Definition::Static(it) => it.try_to_nav(db),
194             Definition::Trait(it) => it.try_to_nav(db),
195             Definition::TypeAlias(it) => it.try_to_nav(db),
196             Definition::BuiltinType(_) => None,
197             Definition::ToolModule(_) => None,
198             Definition::BuiltinAttr(_) => None,
199             // FIXME: The focus range should be set to the helper declaration
200             Definition::DeriveHelper(it) => it.derive().try_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::Macro(it) => it.try_to_nav(db),
217             hir::ModuleDef::BuiltinType(_) => None,
218         }
219     }
220 }
221
222 pub(crate) trait ToNavFromAst {
223     const KIND: SymbolKind;
224 }
225 impl ToNavFromAst for hir::Function {
226     const KIND: SymbolKind = SymbolKind::Function;
227 }
228 impl ToNavFromAst for hir::Const {
229     const KIND: SymbolKind = SymbolKind::Const;
230 }
231 impl ToNavFromAst for hir::Static {
232     const KIND: SymbolKind = SymbolKind::Static;
233 }
234 impl ToNavFromAst for hir::Struct {
235     const KIND: SymbolKind = SymbolKind::Struct;
236 }
237 impl ToNavFromAst for hir::Enum {
238     const KIND: SymbolKind = SymbolKind::Enum;
239 }
240 impl ToNavFromAst for hir::Variant {
241     const KIND: SymbolKind = SymbolKind::Variant;
242 }
243 impl ToNavFromAst for hir::Union {
244     const KIND: SymbolKind = SymbolKind::Union;
245 }
246 impl ToNavFromAst for hir::TypeAlias {
247     const KIND: SymbolKind = SymbolKind::TypeAlias;
248 }
249 impl ToNavFromAst for hir::Trait {
250     const KIND: SymbolKind = SymbolKind::Trait;
251 }
252
253 impl<D> TryToNav for D
254 where
255     D: HasSource + ToNavFromAst + Copy + HasAttrs + HirDisplay,
256     D::Ast: ast::HasName,
257 {
258     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
259         let src = self.source(db)?;
260         let mut res = NavigationTarget::from_named(
261             db,
262             src.as_ref().map(|it| it as &dyn ast::HasName),
263             D::KIND,
264         );
265         res.docs = self.docs(db);
266         res.description = Some(self.display(db).to_string());
267         Some(res)
268     }
269 }
270
271 impl ToNav for hir::Module {
272     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
273         let InFile { file_id, value } = self.definition_source(db);
274
275         let name = self.name(db).map(|it| it.to_smol_str()).unwrap_or_default();
276         let (syntax, focus) = match &value {
277             ModuleSource::SourceFile(node) => (node.syntax(), None),
278             ModuleSource::Module(node) => (
279                 node.syntax(),
280                 node.name().and_then(|it| orig_focus_range(db, file_id, it.syntax())),
281             ),
282             ModuleSource::BlockExpr(node) => (node.syntax(), None),
283         };
284         let FileRange { file_id, range: full_range } =
285             InFile::new(file_id, syntax).original_file_range(db);
286         NavigationTarget::from_syntax(file_id, name, focus, full_range, SymbolKind::Module)
287     }
288 }
289
290 impl TryToNav for hir::Impl {
291     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
292         let InFile { file_id, value } = self.source(db)?;
293         let derive_attr = self.is_builtin_derive(db);
294
295         let focus_range = if derive_attr.is_some() {
296             None
297         } else {
298             value.self_ty().and_then(|ty| orig_focus_range(db, file_id, ty.syntax()))
299         };
300
301         let FileRange { file_id, range: full_range } = match &derive_attr {
302             Some(attr) => attr.syntax().original_file_range(db),
303             None => InFile::new(file_id, value.syntax()).original_file_range(db),
304         };
305
306         Some(NavigationTarget::from_syntax(
307             file_id,
308             "impl".into(),
309             focus_range,
310             full_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 FileRange { file_id, range } =
330                     src.with_value(it.syntax()).original_file_range(db);
331                 NavigationTarget::from_syntax(file_id, "".into(), None, range, SymbolKind::Field)
332             }
333         };
334         Some(field_source)
335     }
336 }
337
338 impl TryToNav for hir::Macro {
339     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
340         let src = self.source(db)?;
341         let name_owner: &dyn ast::HasName = match &src.value {
342             Either::Left(it) => it,
343             Either::Right(it) => it,
344         };
345         let mut res = NavigationTarget::from_named(
346             db,
347             src.as_ref().with_value(name_owner),
348             self.kind(db).into(),
349         );
350         res.docs = self.docs(db);
351         Some(res)
352     }
353 }
354
355 impl TryToNav for hir::Adt {
356     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
357         match self {
358             hir::Adt::Struct(it) => it.try_to_nav(db),
359             hir::Adt::Union(it) => it.try_to_nav(db),
360             hir::Adt::Enum(it) => it.try_to_nav(db),
361         }
362     }
363 }
364
365 impl TryToNav for hir::AssocItem {
366     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
367         match self {
368             AssocItem::Function(it) => it.try_to_nav(db),
369             AssocItem::Const(it) => it.try_to_nav(db),
370             AssocItem::TypeAlias(it) => it.try_to_nav(db),
371         }
372     }
373 }
374
375 impl TryToNav for hir::GenericParam {
376     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
377         match self {
378             hir::GenericParam::TypeParam(it) => it.try_to_nav(db),
379             hir::GenericParam::ConstParam(it) => it.try_to_nav(db),
380             hir::GenericParam::LifetimeParam(it) => it.try_to_nav(db),
381         }
382     }
383 }
384
385 impl ToNav for hir::Local {
386     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
387         let InFile { file_id, value } = self.source(db);
388         let (node, name) = match &value {
389             Either::Left(bind_pat) => (bind_pat.syntax(), bind_pat.name()),
390             Either::Right(it) => (it.syntax(), it.name()),
391         };
392         let focus_range = name.and_then(|it| orig_focus_range(db, file_id, it.syntax()));
393         let FileRange { file_id, range: full_range } =
394             InFile::new(file_id, node).original_file_range(db);
395
396         let name = self.name(db).to_smol_str();
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,
406             name,
407             kind: Some(kind),
408             full_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 InFile { file_id, value } = self.source(db);
420         let name = self.name(db).to_smol_str();
421
422         let range = |syntax: &_| InFile::new(file_id, syntax).original_file_range(db);
423         let FileRange { file_id, range: full_range } = range(value.syntax());
424         let focus_range = value.lifetime().map(|lt| range(lt.syntax()).range);
425
426         NavigationTarget {
427             file_id,
428             name,
429             kind: Some(SymbolKind::Label),
430             full_range,
431             focus_range,
432             container_name: None,
433             description: None,
434             docs: None,
435         }
436     }
437 }
438
439 impl TryToNav for hir::TypeParam {
440     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
441         let InFile { file_id, value } = self.merge().source(db)?;
442         let name = self.name(db).to_smol_str();
443
444         let value = match value {
445             Either::Left(ast::TypeOrConstParam::Type(x)) => Either::Left(x),
446             Either::Left(ast::TypeOrConstParam::Const(_)) => {
447                 never!();
448                 return None;
449             }
450             Either::Right(x) => Either::Right(x),
451         };
452
453         let range = |syntax: &_| InFile::new(file_id, syntax).original_file_range(db);
454         let focus_range = |syntax: &_| InFile::new(file_id, syntax).original_file_range_opt(db);
455         let FileRange { file_id, range: full_range } = match &value {
456             Either::Left(type_param) => range(type_param.syntax()),
457             Either::Right(trait_) => trait_
458                 .name()
459                 .and_then(|name| focus_range(name.syntax()))
460                 .unwrap_or_else(|| range(trait_.syntax())),
461         };
462         let focus_range = value
463             .either(|it| it.name(), |it| it.name())
464             .and_then(|it| focus_range(it.syntax()))
465             .map(|it| it.range);
466         Some(NavigationTarget {
467             file_id,
468             name,
469             kind: Some(SymbolKind::TypeParam),
470             full_range,
471             focus_range,
472             container_name: None,
473             description: None,
474             docs: None,
475         })
476     }
477 }
478
479 impl TryToNav for hir::TypeOrConstParam {
480     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
481         self.split(db).try_to_nav(db)
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.merge().source(db)?;
508         let name = self.name(db).to_smol_str();
509
510         let value = match value {
511             Either::Left(ast::TypeOrConstParam::Const(x)) => x,
512             _ => {
513                 never!();
514                 return None;
515             }
516         };
517
518         let focus_range = value.name().and_then(|it| orig_focus_range(db, file_id, it.syntax()));
519         let FileRange { file_id, range: full_range } =
520             InFile::new(file_id, value.syntax()).original_file_range(db);
521         Some(NavigationTarget {
522             file_id,
523             name,
524             kind: Some(SymbolKind::ConstParam),
525             full_range,
526             focus_range,
527             container_name: None,
528             description: None,
529             docs: None,
530         })
531     }
532 }
533
534 /// Get a description of a symbol.
535 ///
536 /// e.g. `struct Name`, `enum Name`, `fn Name`
537 pub(crate) fn description_from_symbol(db: &RootDatabase, symbol: &FileSymbol) -> Option<String> {
538     let sema = Semantics::new(db);
539     let node = symbol.loc.syntax(&sema)?;
540
541     match_ast! {
542         match node {
543             ast::Fn(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
544             ast::Struct(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
545             ast::Enum(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
546             ast::Trait(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
547             ast::Module(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
548             ast::TypeAlias(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
549             ast::Const(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
550             ast::Static(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
551             ast::RecordField(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
552             ast::Variant(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
553             ast::Union(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
554             _ => None,
555         }
556     }
557 }
558
559 fn orig_focus_range(
560     db: &RootDatabase,
561     file_id: hir::HirFileId,
562     syntax: &SyntaxNode,
563 ) -> Option<TextRange> {
564     InFile::new(file_id, syntax).original_file_range_opt(db).map(|it| it.range)
565 }
566
567 #[cfg(test)]
568 mod tests {
569     use expect_test::expect;
570
571     use crate::{fixture, Query};
572
573     #[test]
574     fn test_nav_for_symbol() {
575         let (analysis, _) = fixture::file(
576             r#"
577 enum FooInner { }
578 fn foo() { enum FooInner { } }
579 "#,
580         );
581
582         let navs = analysis.symbol_search(Query::new("FooInner".to_string())).unwrap();
583         expect![[r#"
584             [
585                 NavigationTarget {
586                     file_id: FileId(
587                         0,
588                     ),
589                     full_range: 0..17,
590                     focus_range: 5..13,
591                     name: "FooInner",
592                     kind: Enum,
593                     description: "enum FooInner",
594                 },
595                 NavigationTarget {
596                     file_id: FileId(
597                         0,
598                     ),
599                     full_range: 29..46,
600                     focus_range: 34..42,
601                     name: "FooInner",
602                     kind: Enum,
603                     container_name: "foo",
604                     description: "enum FooInner",
605                 },
606             ]
607         "#]]
608         .assert_debug_eq(&navs);
609     }
610
611     #[test]
612     fn test_world_symbols_are_case_sensitive() {
613         let (analysis, _) = fixture::file(
614             r#"
615 fn foo() {}
616 struct Foo;
617 "#,
618         );
619
620         let navs = analysis.symbol_search(Query::new("foo".to_string())).unwrap();
621         assert_eq!(navs.len(), 2)
622     }
623 }