]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/navigation_target.rs
Fix syntax highlighting not highlighting derives anymore
[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 = match self.name(db) {
394             Some(it) => it.to_smol_str(),
395             None => "".into(),
396         };
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.source(db)?;
442         let name = self.name(db).to_smol_str();
443
444         let range = |syntax: &_| InFile::new(file_id, syntax).original_file_range(db);
445         let focus_range = |syntax: &_| InFile::new(file_id, syntax).original_file_range_opt(db);
446         let FileRange { file_id, range: full_range } = match &value {
447             Either::Left(type_param) => range(type_param.syntax()),
448             Either::Right(trait_) => trait_
449                 .name()
450                 .and_then(|name| focus_range(name.syntax()))
451                 .unwrap_or_else(|| range(trait_.syntax())),
452         };
453         let focus_range = value
454             .either(|it| it.name(), |it| it.name())
455             .and_then(|it| focus_range(it.syntax()))
456             .map(|it| it.range);
457         Some(NavigationTarget {
458             file_id,
459             name,
460             kind: Some(SymbolKind::TypeParam),
461             full_range,
462             focus_range,
463             container_name: None,
464             description: None,
465             docs: None,
466         })
467     }
468 }
469
470 impl TryToNav for hir::LifetimeParam {
471     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
472         let InFile { file_id, value } = self.source(db)?;
473         let name = self.name(db).to_smol_str();
474
475         let FileRange { file_id, range: full_range } =
476             InFile::new(file_id, value.syntax()).original_file_range(db);
477         Some(NavigationTarget {
478             file_id,
479             name,
480             kind: Some(SymbolKind::LifetimeParam),
481             full_range,
482             focus_range: Some(full_range),
483             container_name: None,
484             description: None,
485             docs: None,
486         })
487     }
488 }
489
490 impl TryToNav for hir::ConstParam {
491     fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
492         let InFile { file_id, value } = self.source(db)?;
493         let name = self.name(db).to_smol_str();
494
495         let focus_range = value.name().and_then(|it| orig_focus_range(db, file_id, it.syntax()));
496         let FileRange { file_id, range: full_range } =
497             InFile::new(file_id, value.syntax()).original_file_range(db);
498         Some(NavigationTarget {
499             file_id,
500             name,
501             kind: Some(SymbolKind::ConstParam),
502             full_range,
503             focus_range,
504             container_name: None,
505             description: None,
506             docs: None,
507         })
508     }
509 }
510
511 /// Get a description of a symbol.
512 ///
513 /// e.g. `struct Name`, `enum Name`, `fn Name`
514 pub(crate) fn description_from_symbol(db: &RootDatabase, symbol: &FileSymbol) -> Option<String> {
515     let sema = Semantics::new(db);
516     let node = symbol.loc.syntax(&sema)?;
517
518     match_ast! {
519         match node {
520             ast::Fn(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
521             ast::Struct(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
522             ast::Enum(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
523             ast::Trait(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
524             ast::Module(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
525             ast::TypeAlias(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
526             ast::Const(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
527             ast::Static(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
528             ast::RecordField(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
529             ast::Variant(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
530             ast::Union(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
531             _ => None,
532         }
533     }
534 }
535
536 fn orig_focus_range(
537     db: &RootDatabase,
538     file_id: hir::HirFileId,
539     syntax: &SyntaxNode,
540 ) -> Option<TextRange> {
541     InFile::new(file_id, syntax).original_file_range_opt(db).map(|it| it.range)
542 }
543
544 #[cfg(test)]
545 mod tests {
546     use expect_test::expect;
547
548     use crate::{fixture, Query};
549
550     #[test]
551     fn test_nav_for_symbol() {
552         let (analysis, _) = fixture::file(
553             r#"
554 enum FooInner { }
555 fn foo() { enum FooInner { } }
556 "#,
557         );
558
559         let navs = analysis.symbol_search(Query::new("FooInner".to_string())).unwrap();
560         expect![[r#"
561             [
562                 NavigationTarget {
563                     file_id: FileId(
564                         0,
565                     ),
566                     full_range: 0..17,
567                     focus_range: 5..13,
568                     name: "FooInner",
569                     kind: Enum,
570                     description: "enum FooInner",
571                 },
572                 NavigationTarget {
573                     file_id: FileId(
574                         0,
575                     ),
576                     full_range: 29..46,
577                     focus_range: 34..42,
578                     name: "FooInner",
579                     kind: Enum,
580                     container_name: "foo",
581                     description: "enum FooInner",
582                 },
583             ]
584         "#]]
585         .assert_debug_eq(&navs);
586     }
587
588     #[test]
589     fn test_world_symbols_are_case_sensitive() {
590         let (analysis, _) = fixture::file(
591             r#"
592 fn foo() {}
593 struct Foo;
594 "#,
595         );
596
597         let navs = analysis.symbol_search(Query::new("foo".to_string())).unwrap();
598         assert_eq!(navs.len(), 2)
599     }
600 }