]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/display/navigation_target.rs
Merge #6914
[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, LIFETIME_PARAM, 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             Definition::LifetimeParam(it) => Some(it.to_nav(db)),
186         }
187     }
188 }
189
190 impl TryToNav for hir::ModuleDef {
191     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
192         let res = match self {
193             hir::ModuleDef::Module(it) => it.to_nav(db),
194             hir::ModuleDef::Function(it) => it.to_nav(db),
195             hir::ModuleDef::Adt(it) => it.to_nav(db),
196             hir::ModuleDef::EnumVariant(it) => it.to_nav(db),
197             hir::ModuleDef::Const(it) => it.to_nav(db),
198             hir::ModuleDef::Static(it) => it.to_nav(db),
199             hir::ModuleDef::Trait(it) => it.to_nav(db),
200             hir::ModuleDef::TypeAlias(it) => it.to_nav(db),
201             hir::ModuleDef::BuiltinType(_) => return None,
202         };
203         Some(res)
204     }
205 }
206
207 pub(crate) trait ToNavFromAst {}
208 impl ToNavFromAst for hir::Function {}
209 impl ToNavFromAst for hir::Const {}
210 impl ToNavFromAst for hir::Static {}
211 impl ToNavFromAst for hir::Struct {}
212 impl ToNavFromAst for hir::Enum {}
213 impl ToNavFromAst for hir::EnumVariant {}
214 impl ToNavFromAst for hir::Union {}
215 impl ToNavFromAst for hir::TypeAlias {}
216 impl ToNavFromAst for hir::Trait {}
217
218 impl<D> ToNav for D
219 where
220     D: HasSource + ToNavFromAst + Copy + HasAttrs,
221     D::Ast: ast::NameOwner + ShortLabel,
222 {
223     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
224         let src = self.source(db);
225         let mut res =
226             NavigationTarget::from_named(db, src.as_ref().map(|it| it as &dyn ast::NameOwner));
227         res.docs = self.docs(db);
228         res.description = src.value.short_label();
229         res
230     }
231 }
232
233 impl ToNav for hir::Module {
234     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
235         let src = self.definition_source(db);
236         let name = self.name(db).map(|it| it.to_string().into()).unwrap_or_default();
237         let (syntax, focus) = match &src.value {
238             ModuleSource::SourceFile(node) => (node.syntax(), None),
239             ModuleSource::Module(node) => {
240                 (node.syntax(), node.name().map(|it| it.syntax().text_range()))
241             }
242         };
243         let frange = src.with_value(syntax).original_file_range(db);
244         NavigationTarget::from_syntax(frange.file_id, name, focus, frange.range, syntax.kind())
245     }
246 }
247
248 impl ToNav for hir::Impl {
249     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
250         let src = self.source(db);
251         let derive_attr = self.is_builtin_derive(db);
252         let frange = if let Some(item) = &derive_attr {
253             item.syntax().original_file_range(db)
254         } else {
255             src.as_ref().map(|it| it.syntax()).original_file_range(db)
256         };
257         let focus_range = if derive_attr.is_some() {
258             None
259         } else {
260             src.value.self_ty().map(|ty| src.with_value(ty.syntax()).original_file_range(db).range)
261         };
262
263         NavigationTarget::from_syntax(
264             frange.file_id,
265             "impl".into(),
266             focus_range,
267             frange.range,
268             src.value.syntax().kind(),
269         )
270     }
271 }
272
273 impl ToNav for hir::Field {
274     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
275         let src = self.source(db);
276
277         match &src.value {
278             FieldSource::Named(it) => {
279                 let mut res = NavigationTarget::from_named(db, src.with_value(it));
280                 res.docs = self.docs(db);
281                 res.description = it.short_label();
282                 res
283             }
284             FieldSource::Pos(it) => {
285                 let frange = src.with_value(it.syntax()).original_file_range(db);
286                 NavigationTarget::from_syntax(
287                     frange.file_id,
288                     "".into(),
289                     None,
290                     frange.range,
291                     it.syntax().kind(),
292                 )
293             }
294         }
295     }
296 }
297
298 impl ToNav for hir::MacroDef {
299     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
300         let src = self.source(db);
301         log::debug!("nav target {:#?}", src.value.syntax());
302         let mut res =
303             NavigationTarget::from_named(db, src.as_ref().map(|it| it as &dyn ast::NameOwner));
304         res.docs = self.docs(db);
305         res
306     }
307 }
308
309 impl ToNav for hir::Adt {
310     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
311         match self {
312             hir::Adt::Struct(it) => it.to_nav(db),
313             hir::Adt::Union(it) => it.to_nav(db),
314             hir::Adt::Enum(it) => it.to_nav(db),
315         }
316     }
317 }
318
319 impl ToNav for hir::AssocItem {
320     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
321         match self {
322             AssocItem::Function(it) => it.to_nav(db),
323             AssocItem::Const(it) => it.to_nav(db),
324             AssocItem::TypeAlias(it) => it.to_nav(db),
325         }
326     }
327 }
328
329 impl ToNav for hir::Local {
330     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
331         let src = self.source(db);
332         let node = match &src.value {
333             Either::Left(bind_pat) => {
334                 bind_pat.name().map_or_else(|| bind_pat.syntax().clone(), |it| it.syntax().clone())
335             }
336             Either::Right(it) => it.syntax().clone(),
337         };
338         let full_range = src.with_value(&node).original_file_range(db);
339         let name = match self.name(db) {
340             Some(it) => it.to_string().into(),
341             None => "".into(),
342         };
343         NavigationTarget {
344             file_id: full_range.file_id,
345             name,
346             kind: IDENT_PAT,
347             full_range: full_range.range,
348             focus_range: None,
349             container_name: None,
350             description: None,
351             docs: None,
352         }
353     }
354 }
355
356 impl ToNav for hir::TypeParam {
357     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
358         let src = self.source(db);
359         let full_range = match &src.value {
360             Either::Left(it) => it.syntax().text_range(),
361             Either::Right(it) => it.syntax().text_range(),
362         };
363         let focus_range = match &src.value {
364             Either::Left(_) => None,
365             Either::Right(it) => it.name().map(|it| it.syntax().text_range()),
366         };
367         NavigationTarget {
368             file_id: src.file_id.original_file(db),
369             name: self.name(db).to_string().into(),
370             kind: TYPE_PARAM,
371             full_range,
372             focus_range,
373             container_name: None,
374             description: None,
375             docs: None,
376         }
377     }
378 }
379
380 impl ToNav for hir::LifetimeParam {
381     fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
382         let src = self.source(db);
383         let full_range = src.value.syntax().text_range();
384         NavigationTarget {
385             file_id: src.file_id.original_file(db),
386             name: self.name(db).to_string().into(),
387             kind: LIFETIME_PARAM,
388             full_range,
389             focus_range: Some(full_range),
390             container_name: None,
391             description: None,
392             docs: None,
393         }
394     }
395 }
396
397 pub(crate) fn docs_from_symbol(db: &RootDatabase, symbol: &FileSymbol) -> Option<Documentation> {
398     let parse = db.parse(symbol.file_id);
399     let node = symbol.ptr.to_node(parse.tree().syntax());
400     let file_id = HirFileId::from(symbol.file_id);
401
402     let it = match_ast! {
403         match node {
404             ast::Fn(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
405             ast::Struct(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
406             ast::Enum(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
407             ast::Trait(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
408             ast::Module(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
409             ast::TypeAlias(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
410             ast::Const(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
411             ast::Static(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
412             ast::RecordField(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
413             ast::Variant(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
414             ast::MacroCall(it) => hir::Attrs::from_attrs_owner(db, InFile::new(file_id, &it)),
415             _ => return None,
416         }
417     };
418     it.docs()
419 }
420
421 /// Get a description of a symbol.
422 ///
423 /// e.g. `struct Name`, `enum Name`, `fn Name`
424 pub(crate) fn description_from_symbol(db: &RootDatabase, symbol: &FileSymbol) -> Option<String> {
425     let parse = db.parse(symbol.file_id);
426     let node = symbol.ptr.to_node(parse.tree().syntax());
427
428     match_ast! {
429         match node {
430             ast::Fn(it) => it.short_label(),
431             ast::Struct(it) => it.short_label(),
432             ast::Enum(it) => it.short_label(),
433             ast::Trait(it) => it.short_label(),
434             ast::Module(it) => it.short_label(),
435             ast::TypeAlias(it) => it.short_label(),
436             ast::Const(it) => it.short_label(),
437             ast::Static(it) => it.short_label(),
438             ast::RecordField(it) => it.short_label(),
439             ast::Variant(it) => it.short_label(),
440             _ => None,
441         }
442     }
443 }
444
445 #[cfg(test)]
446 mod tests {
447     use expect_test::expect;
448
449     use crate::{fixture, Query};
450
451     #[test]
452     fn test_nav_for_symbol() {
453         let (analysis, _) = fixture::file(
454             r#"
455 enum FooInner { }
456 fn foo() { enum FooInner { } }
457 "#,
458         );
459
460         let navs = analysis.symbol_search(Query::new("FooInner".to_string())).unwrap();
461         expect![[r#"
462             [
463                 NavigationTarget {
464                     file_id: FileId(
465                         0,
466                     ),
467                     full_range: 0..17,
468                     focus_range: Some(
469                         5..13,
470                     ),
471                     name: "FooInner",
472                     kind: ENUM,
473                     container_name: None,
474                     description: Some(
475                         "enum FooInner",
476                     ),
477                     docs: None,
478                 },
479                 NavigationTarget {
480                     file_id: FileId(
481                         0,
482                     ),
483                     full_range: 29..46,
484                     focus_range: Some(
485                         34..42,
486                     ),
487                     name: "FooInner",
488                     kind: ENUM,
489                     container_name: Some(
490                         "foo",
491                     ),
492                     description: Some(
493                         "enum FooInner",
494                     ),
495                     docs: None,
496                 },
497             ]
498         "#]]
499         .assert_debug_eq(&navs);
500     }
501
502     #[test]
503     fn test_world_symbols_are_case_sensitive() {
504         let (analysis, _) = fixture::file(
505             r#"
506 fn foo() {}
507 struct Foo;
508 "#,
509         );
510
511         let navs = analysis.symbol_search(Query::new("foo".to_string())).unwrap();
512         assert_eq!(navs.len(), 2)
513     }
514 }