]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/display/navigation_target.rs
Merge #6818
[rust.git] / crates / ide / src / display / navigation_target.rs
1 //! FIXME: write short doc here
2
3 use either::Either;
4 use hir::{
5     AssocItem, Documentation, FieldSource, HasAttrs, HasSource, HirFileId, InFile, ModuleSource,
6 };
7 use ide_db::base_db::{FileId, SourceDatabase};
8 use ide_db::{defs::Definition, RootDatabase};
9 use syntax::{
10     ast::{self, NameOwner},
11     match_ast, AstNode, SmolStr,
12     SyntaxKind::{self, IDENT_PAT, TYPE_PARAM},
13     TextRange,
14 };
15
16 use crate::FileSymbol;
17
18 use super::short_label::ShortLabel;
19
20 /// `NavigationTarget` represents and 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(Debug, 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 withing 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. "Most
39     /// interesting" range within the full range, typically the range of
40     /// 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: SyntaxKind,
46     pub container_name: Option<SmolStr>,
47     pub description: Option<String>,
48     pub docs: Option<Documentation>,
49 }
50
51 pub(crate) trait ToNav {
52     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget;
53 }
54
55 pub(crate) trait TryToNav {
56     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget>;
57 }
58
59 impl NavigationTarget {
60     pub fn focus_or_full_range(&self) -> TextRange {
61         self.focus_range.unwrap_or(self.full_range)
62     }
63
64     pub(crate) fn from_module_to_decl(db: &RootDatabase, module: hir::Module) -> NavigationTarget {
65         let name = module.name(db).map(|it| it.to_string().into()).unwrap_or_default();
66         if let Some(src) = module.declaration_source(db) {
67             let node = src.as_ref().map(|it| it.syntax());
68             let frange = node.original_file_range(db);
69             let mut res = NavigationTarget::from_syntax(
70                 frange.file_id,
71                 name,
72                 None,
73                 frange.range,
74                 src.value.syntax().kind(),
75             );
76             res.docs = module.attrs(db).docs();
77             res.description = src.value.short_label();
78             return res;
79         }
80         module.to_nav(db)
81     }
82
83     #[cfg(test)]
84     pub(crate) fn assert_match(&self, expected: &str) {
85         let actual = self.debug_render();
86         test_utils::assert_eq_text!(expected.trim(), actual.trim(),);
87     }
88
89     #[cfg(test)]
90     pub(crate) fn debug_render(&self) -> String {
91         let mut buf =
92             format!("{} {:?} {:?} {:?}", self.name, self.kind, self.file_id, self.full_range);
93         if let Some(focus_range) = self.focus_range {
94             buf.push_str(&format!(" {:?}", focus_range))
95         }
96         if let Some(container_name) = &self.container_name {
97             buf.push_str(&format!(" {}", container_name))
98         }
99         buf
100     }
101
102     /// Allows `NavigationTarget` to be created from a `NameOwner`
103     pub(crate) fn from_named(
104         db: &RootDatabase,
105         node: InFile<&dyn ast::NameOwner>,
106     ) -> NavigationTarget {
107         let name =
108             node.value.name().map(|it| it.text().clone()).unwrap_or_else(|| SmolStr::new("_"));
109         let focus_range =
110             node.value.name().map(|it| node.with_value(it.syntax()).original_file_range(db).range);
111         let frange = node.map(|it| it.syntax()).original_file_range(db);
112
113         NavigationTarget::from_syntax(
114             frange.file_id,
115             name,
116             focus_range,
117             frange.range,
118             node.value.syntax().kind(),
119         )
120     }
121
122     /// Allows `NavigationTarget` to be created from a `DocCommentsOwner` and a `NameOwner`
123     pub(crate) fn from_doc_commented(
124         db: &RootDatabase,
125         named: InFile<&dyn ast::NameOwner>,
126         node: InFile<&dyn ast::DocCommentsOwner>,
127     ) -> NavigationTarget {
128         let name =
129             named.value.name().map(|it| it.text().clone()).unwrap_or_else(|| SmolStr::new("_"));
130         let frange = node.map(|it| it.syntax()).original_file_range(db);
131
132         NavigationTarget::from_syntax(
133             frange.file_id,
134             name,
135             None,
136             frange.range,
137             node.value.syntax().kind(),
138         )
139     }
140
141     fn from_syntax(
142         file_id: FileId,
143         name: SmolStr,
144         focus_range: Option<TextRange>,
145         full_range: TextRange,
146         kind: SyntaxKind,
147     ) -> NavigationTarget {
148         NavigationTarget {
149             file_id,
150             name,
151             kind,
152             full_range,
153             focus_range,
154             container_name: None,
155             description: None,
156             docs: None,
157         }
158     }
159 }
160
161 impl ToNav for FileSymbol {
162     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
163         NavigationTarget {
164             file_id: self.file_id,
165             name: self.name.clone(),
166             kind: self.kind,
167             full_range: self.range,
168             focus_range: self.name_range,
169             container_name: self.container_name.clone(),
170             description: description_from_symbol(db, self),
171             docs: docs_from_symbol(db, self),
172         }
173     }
174 }
175
176 impl TryToNav for Definition {
177     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
178         match self {
179             Definition::Macro(it) => Some(it.to_nav(db)),
180             Definition::Field(it) => Some(it.to_nav(db)),
181             Definition::ModuleDef(it) => it.try_to_nav(db),
182             Definition::SelfType(it) => Some(it.to_nav(db)),
183             Definition::Local(it) => Some(it.to_nav(db)),
184             Definition::TypeParam(it) => Some(it.to_nav(db)),
185         }
186     }
187 }
188
189 impl TryToNav for hir::ModuleDef {
190     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
191         let res = match self {
192             hir::ModuleDef::Module(it) => it.to_nav(db),
193             hir::ModuleDef::Function(it) => it.to_nav(db),
194             hir::ModuleDef::Adt(it) => it.to_nav(db),
195             hir::ModuleDef::EnumVariant(it) => it.to_nav(db),
196             hir::ModuleDef::Const(it) => it.to_nav(db),
197             hir::ModuleDef::Static(it) => it.to_nav(db),
198             hir::ModuleDef::Trait(it) => it.to_nav(db),
199             hir::ModuleDef::TypeAlias(it) => it.to_nav(db),
200             hir::ModuleDef::BuiltinType(_) => return None,
201         };
202         Some(res)
203     }
204 }
205
206 pub(crate) trait ToNavFromAst {}
207 impl ToNavFromAst for hir::Function {}
208 impl ToNavFromAst for hir::Const {}
209 impl ToNavFromAst for hir::Static {}
210 impl ToNavFromAst for hir::Struct {}
211 impl ToNavFromAst for hir::Enum {}
212 impl ToNavFromAst for hir::EnumVariant {}
213 impl ToNavFromAst for hir::Union {}
214 impl ToNavFromAst for hir::TypeAlias {}
215 impl ToNavFromAst for hir::Trait {}
216
217 impl<D> ToNav for D
218 where
219     D: HasSource + ToNavFromAst + Copy + HasAttrs,
220     D::Ast: ast::NameOwner + ShortLabel,
221 {
222     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
223         let src = self.source(db);
224         let mut res =
225             NavigationTarget::from_named(db, src.as_ref().map(|it| it as &dyn ast::NameOwner));
226         res.docs = self.docs(db);
227         res.description = src.value.short_label();
228         res
229     }
230 }
231
232 impl ToNav for hir::Module {
233     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
234         let src = self.definition_source(db);
235         let name = self.name(db).map(|it| it.to_string().into()).unwrap_or_default();
236         let (syntax, focus) = match &src.value {
237             ModuleSource::SourceFile(node) => (node.syntax(), None),
238             ModuleSource::Module(node) => {
239                 (node.syntax(), node.name().map(|it| it.syntax().text_range()))
240             }
241         };
242         let frange = src.with_value(syntax).original_file_range(db);
243         NavigationTarget::from_syntax(frange.file_id, name, focus, frange.range, syntax.kind())
244     }
245 }
246
247 impl ToNav for hir::ImplDef {
248     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
249         let src = self.source(db);
250         let derive_attr = self.is_builtin_derive(db);
251         let frange = if let Some(item) = &derive_attr {
252             item.syntax().original_file_range(db)
253         } else {
254             src.as_ref().map(|it| it.syntax()).original_file_range(db)
255         };
256         let focus_range = if derive_attr.is_some() {
257             None
258         } else {
259             src.value.self_ty().map(|ty| src.with_value(ty.syntax()).original_file_range(db).range)
260         };
261
262         NavigationTarget::from_syntax(
263             frange.file_id,
264             "impl".into(),
265             focus_range,
266             frange.range,
267             src.value.syntax().kind(),
268         )
269     }
270 }
271
272 impl ToNav for hir::Field {
273     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
274         let src = self.source(db);
275
276         match &src.value {
277             FieldSource::Named(it) => {
278                 let mut res = NavigationTarget::from_named(db, src.with_value(it));
279                 res.docs = self.docs(db);
280                 res.description = it.short_label();
281                 res
282             }
283             FieldSource::Pos(it) => {
284                 let frange = src.with_value(it.syntax()).original_file_range(db);
285                 NavigationTarget::from_syntax(
286                     frange.file_id,
287                     "".into(),
288                     None,
289                     frange.range,
290                     it.syntax().kind(),
291                 )
292             }
293         }
294     }
295 }
296
297 impl ToNav for hir::MacroDef {
298     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
299         let src = self.source(db);
300         log::debug!("nav target {:#?}", src.value.syntax());
301         let mut res =
302             NavigationTarget::from_named(db, src.as_ref().map(|it| it as &dyn ast::NameOwner));
303         res.docs = self.docs(db);
304         res
305     }
306 }
307
308 impl ToNav for hir::Adt {
309     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
310         match self {
311             hir::Adt::Struct(it) => it.to_nav(db),
312             hir::Adt::Union(it) => it.to_nav(db),
313             hir::Adt::Enum(it) => it.to_nav(db),
314         }
315     }
316 }
317
318 impl ToNav for hir::AssocItem {
319     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
320         match self {
321             AssocItem::Function(it) => it.to_nav(db),
322             AssocItem::Const(it) => it.to_nav(db),
323             AssocItem::TypeAlias(it) => it.to_nav(db),
324         }
325     }
326 }
327
328 impl ToNav for hir::Local {
329     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
330         let src = self.source(db);
331         let node = match &src.value {
332             Either::Left(bind_pat) => {
333                 bind_pat.name().map_or_else(|| bind_pat.syntax().clone(), |it| it.syntax().clone())
334             }
335             Either::Right(it) => it.syntax().clone(),
336         };
337         let full_range = src.with_value(&node).original_file_range(db);
338         let name = match self.name(db) {
339             Some(it) => it.to_string().into(),
340             None => "".into(),
341         };
342         NavigationTarget {
343             file_id: full_range.file_id,
344             name,
345             kind: IDENT_PAT,
346             full_range: full_range.range,
347             focus_range: None,
348             container_name: None,
349             description: None,
350             docs: None,
351         }
352     }
353 }
354
355 impl ToNav for hir::TypeParam {
356     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
357         let src = self.source(db);
358         let full_range = match &src.value {
359             Either::Left(it) => it.syntax().text_range(),
360             Either::Right(it) => it.syntax().text_range(),
361         };
362         let focus_range = match &src.value {
363             Either::Left(_) => None,
364             Either::Right(it) => it.name().map(|it| it.syntax().text_range()),
365         };
366         NavigationTarget {
367             file_id: src.file_id.original_file(db),
368             name: self.name(db).to_string().into(),
369             kind: TYPE_PARAM,
370             full_range,
371             focus_range,
372             container_name: None,
373             description: None,
374             docs: None,
375         }
376     }
377 }
378
379 pub(crate) fn docs_from_symbol(db: &RootDatabase, symbol: &FileSymbol) -> Option<Documentation> {
380     let parse = db.parse(symbol.file_id);
381     let node = symbol.ptr.to_node(parse.tree().syntax());
382     let file_id = HirFileId::from(symbol.file_id);
383
384     let it = match_ast! {
385         match node {
386             ast::Fn(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
387             ast::Struct(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
388             ast::Enum(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
389             ast::Trait(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
390             ast::Module(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
391             ast::TypeAlias(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
392             ast::Const(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
393             ast::Static(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
394             ast::RecordField(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
395             ast::Variant(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
396             ast::MacroCall(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
397             _ => return None,
398         }
399     };
400     it.docs()
401 }
402
403 /// Get a description of a symbol.
404 ///
405 /// e.g. `struct Name`, `enum Name`, `fn Name`
406 pub(crate) fn description_from_symbol(db: &RootDatabase, symbol: &FileSymbol) -> Option<String> {
407     let parse = db.parse(symbol.file_id);
408     let node = symbol.ptr.to_node(parse.tree().syntax());
409
410     match_ast! {
411         match node {
412             ast::Fn(it) => it.short_label(),
413             ast::Struct(it) => it.short_label(),
414             ast::Enum(it) => it.short_label(),
415             ast::Trait(it) => it.short_label(),
416             ast::Module(it) => it.short_label(),
417             ast::TypeAlias(it) => it.short_label(),
418             ast::Const(it) => it.short_label(),
419             ast::Static(it) => it.short_label(),
420             ast::RecordField(it) => it.short_label(),
421             ast::Variant(it) => it.short_label(),
422             _ => None,
423         }
424     }
425 }
426
427 #[cfg(test)]
428 mod tests {
429     use expect_test::expect;
430
431     use crate::{fixture, Query};
432
433     #[test]
434     fn test_nav_for_symbol() {
435         let (analysis, _) = fixture::file(
436             r#"
437 enum FooInner { }
438 fn foo() { enum FooInner { } }
439 "#,
440         );
441
442         let navs = analysis.symbol_search(Query::new("FooInner".to_string())).unwrap();
443         expect![[r#"
444             [
445                 NavigationTarget {
446                     file_id: FileId(
447                         0,
448                     ),
449                     full_range: 0..17,
450                     focus_range: Some(
451                         5..13,
452                     ),
453                     name: "FooInner",
454                     kind: ENUM,
455                     container_name: None,
456                     description: Some(
457                         "enum FooInner",
458                     ),
459                     docs: None,
460                 },
461                 NavigationTarget {
462                     file_id: FileId(
463                         0,
464                     ),
465                     full_range: 29..46,
466                     focus_range: Some(
467                         34..42,
468                     ),
469                     name: "FooInner",
470                     kind: ENUM,
471                     container_name: Some(
472                         "foo",
473                     ),
474                     description: Some(
475                         "enum FooInner",
476                     ),
477                     docs: None,
478                 },
479             ]
480         "#]]
481         .assert_debug_eq(&navs);
482     }
483
484     #[test]
485     fn test_world_symbols_are_case_sensitive() {
486         let (analysis, _) = fixture::file(
487             r#"
488 fn foo() {}
489 struct Foo;
490 "#,
491         );
492
493         let navs = analysis.symbol_search(Query::new("foo".to_string())).unwrap();
494         assert_eq!(navs.len(), 2)
495     }
496 }