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