1 //! See [`NavigationTarget`].
7 AssocItem, Documentation, FieldSource, HasAttrs, HasSource, HirDisplay, InFile, ModuleSource,
11 base_db::{FileId, FileRange},
14 use ide_db::{defs::Definition, RootDatabase};
17 match_ast, AstNode, SmolStr, TextRange,
20 use crate::FileSymbol;
22 /// `NavigationTarget` represents an element in the editor's UI which you can
23 /// click on to navigate to a particular piece of code.
25 /// Typically, a `NavigationTarget` corresponds to some element in the source
26 /// code, like a function or a struct, but this is not strictly required.
27 #[derive(Clone, PartialEq, Eq, Hash)]
28 pub struct NavigationTarget {
30 /// Range which encompasses the whole element.
32 /// Should include body, doc comments, attributes, etc.
34 /// Clients should use this range to answer "is the cursor inside the
35 /// element?" question.
36 pub full_range: TextRange,
37 /// A "most interesting" range within the `full_range`.
39 /// Typically, `full_range` is the whole syntax node, including doc
40 /// comments, and `focus_range` is the range of the identifier.
42 /// Clients should place the cursor on this range when navigating to this target.
43 pub focus_range: Option<TextRange>,
45 pub kind: Option<SymbolKind>,
46 pub container_name: Option<SmolStr>,
47 pub description: Option<String>,
48 pub docs: Option<Documentation>,
51 impl fmt::Debug for NavigationTarget {
52 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53 let mut f = f.debug_struct("NavigationTarget");
55 ($($name:ident)*) => {$(
56 if let Some(it) = &self.$name {
57 f.field(stringify!($name), it);
61 f.field("file_id", &self.file_id).field("full_range", &self.full_range);
63 f.field("name", &self.name);
64 opt!(kind container_name description docs);
69 pub(crate) trait ToNav {
70 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget;
73 pub(crate) trait TryToNav {
74 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget>;
77 impl<T: TryToNav, U: TryToNav> TryToNav for Either<T, U> {
78 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
80 Either::Left(it) => it.try_to_nav(db),
81 Either::Right(it) => it.try_to_nav(db),
86 impl NavigationTarget {
87 pub fn focus_or_full_range(&self) -> TextRange {
88 self.focus_range.unwrap_or(self.full_range)
91 pub(crate) fn from_module_to_decl(db: &RootDatabase, module: hir::Module) -> NavigationTarget {
92 let name = module.name(db).map(|it| it.to_smol_str()).unwrap_or_default();
93 if let Some(src @ InFile { value, .. }) = &module.declaration_source(db) {
94 let FileRange { file_id, range: full_range } = src.syntax().original_file_range(db);
95 let focus_range = value
97 .and_then(|name| src.with_value(name.syntax()).original_file_range_opt(db))
99 let mut res = NavigationTarget::from_syntax(
106 res.docs = module.attrs(db).docs();
107 res.description = Some(module.display(db).to_string());
114 pub(crate) fn debug_render(&self) -> String {
115 let mut buf = format!(
122 if let Some(focus_range) = self.focus_range {
123 buf.push_str(&format!(" {:?}", focus_range))
125 if let Some(container_name) = &self.container_name {
126 buf.push_str(&format!(" {}", container_name))
131 /// Allows `NavigationTarget` to be created from a `NameOwner`
132 pub(crate) fn from_named(
134 node: InFile<&dyn ast::HasName>,
136 ) -> NavigationTarget {
137 let name = node.value.name().map(|it| it.text().into()).unwrap_or_else(|| "_".into());
138 let focus_range = node
141 .and_then(|it| node.with_value(it.syntax()).original_file_range_opt(db))
143 let FileRange { file_id, range } = node.map(|it| it.syntax()).original_file_range(db);
145 NavigationTarget::from_syntax(file_id, name, focus_range, range, kind)
151 focus_range: Option<TextRange>,
152 full_range: TextRange,
154 ) -> NavigationTarget {
161 container_name: None,
168 impl TryToNav for FileSymbol {
169 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
170 let full_range = self.loc.original_range(db)?;
171 let name_range = self.loc.original_name_range(db)?;
173 Some(NavigationTarget {
174 file_id: full_range.file_id,
175 name: self.name.clone(),
176 kind: Some(self.kind.into()),
177 full_range: full_range.range,
178 focus_range: Some(name_range.range),
179 container_name: self.container_name.clone(),
180 description: description_from_symbol(db, self),
186 impl TryToNav for Definition {
187 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
189 Definition::Local(it) => Some(it.to_nav(db)),
190 Definition::Label(it) => Some(it.to_nav(db)),
191 Definition::Module(it) => Some(it.to_nav(db)),
192 Definition::Macro(it) => it.try_to_nav(db),
193 Definition::Field(it) => it.try_to_nav(db),
194 Definition::SelfType(it) => it.try_to_nav(db),
195 Definition::GenericParam(it) => it.try_to_nav(db),
196 Definition::Function(it) => it.try_to_nav(db),
197 Definition::Adt(it) => it.try_to_nav(db),
198 Definition::Variant(it) => it.try_to_nav(db),
199 Definition::Const(it) => it.try_to_nav(db),
200 Definition::Static(it) => it.try_to_nav(db),
201 Definition::Trait(it) => it.try_to_nav(db),
202 Definition::TypeAlias(it) => it.try_to_nav(db),
203 Definition::BuiltinType(_) => None,
204 Definition::ToolModule(_) => None,
205 Definition::BuiltinAttr(_) => None,
210 impl TryToNav for hir::ModuleDef {
211 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
213 hir::ModuleDef::Module(it) => Some(it.to_nav(db)),
214 hir::ModuleDef::Function(it) => it.try_to_nav(db),
215 hir::ModuleDef::Adt(it) => it.try_to_nav(db),
216 hir::ModuleDef::Variant(it) => it.try_to_nav(db),
217 hir::ModuleDef::Const(it) => it.try_to_nav(db),
218 hir::ModuleDef::Static(it) => it.try_to_nav(db),
219 hir::ModuleDef::Trait(it) => it.try_to_nav(db),
220 hir::ModuleDef::TypeAlias(it) => it.try_to_nav(db),
221 hir::ModuleDef::BuiltinType(_) => None,
226 pub(crate) trait ToNavFromAst {
227 const KIND: SymbolKind;
229 impl ToNavFromAst for hir::Function {
230 const KIND: SymbolKind = SymbolKind::Function;
232 impl ToNavFromAst for hir::Const {
233 const KIND: SymbolKind = SymbolKind::Const;
235 impl ToNavFromAst for hir::Static {
236 const KIND: SymbolKind = SymbolKind::Static;
238 impl ToNavFromAst for hir::Struct {
239 const KIND: SymbolKind = SymbolKind::Struct;
241 impl ToNavFromAst for hir::Enum {
242 const KIND: SymbolKind = SymbolKind::Enum;
244 impl ToNavFromAst for hir::Variant {
245 const KIND: SymbolKind = SymbolKind::Variant;
247 impl ToNavFromAst for hir::Union {
248 const KIND: SymbolKind = SymbolKind::Union;
250 impl ToNavFromAst for hir::TypeAlias {
251 const KIND: SymbolKind = SymbolKind::TypeAlias;
253 impl ToNavFromAst for hir::Trait {
254 const KIND: SymbolKind = SymbolKind::Trait;
257 impl<D> TryToNav for D
259 D: HasSource + ToNavFromAst + Copy + HasAttrs + HirDisplay,
260 D::Ast: ast::HasName,
262 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
263 let src = self.source(db)?;
264 let mut res = NavigationTarget::from_named(
266 src.as_ref().map(|it| it as &dyn ast::HasName),
269 res.docs = self.docs(db);
270 res.description = Some(self.display(db).to_string());
275 impl ToNav for hir::Module {
276 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
277 let InFile { file_id, value } = self.definition_source(db);
279 let name = self.name(db).map(|it| it.to_smol_str()).unwrap_or_default();
280 let (syntax, focus) = match &value {
281 ModuleSource::SourceFile(node) => (node.syntax(), None),
282 ModuleSource::Module(node) => (
285 .and_then(|it| InFile::new(file_id, it.syntax()).original_file_range_opt(db))
288 ModuleSource::BlockExpr(node) => (node.syntax(), None),
290 let FileRange { file_id, range: full_range } =
291 InFile::new(file_id, syntax).original_file_range(db);
292 NavigationTarget::from_syntax(file_id, name, focus, full_range, SymbolKind::Module)
296 impl TryToNav for hir::Impl {
297 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
298 let InFile { file_id, value } = self.source(db)?;
299 let derive_attr = self.is_builtin_derive(db);
301 let range = |syntax: &_| InFile::new(file_id, syntax).original_file_range(db);
302 let focus_range = if derive_attr.is_some() {
307 .and_then(|ty| InFile::new(file_id, ty.syntax()).original_file_range_opt(db))
310 let FileRange { file_id, range: full_range } = match &derive_attr {
311 Some(InFile { value, .. }) => range(value.syntax()),
312 None => range(value.syntax()),
315 Some(NavigationTarget::from_syntax(
325 impl TryToNav for hir::Field {
326 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
327 let src = self.source(db)?;
329 let field_source = match &src.value {
330 FieldSource::Named(it) => {
332 NavigationTarget::from_named(db, src.with_value(it), SymbolKind::Field);
333 res.docs = self.docs(db);
334 res.description = Some(self.display(db).to_string());
337 FieldSource::Pos(it) => {
338 let FileRange { file_id, range } =
339 src.with_value(it.syntax()).original_file_range(db);
340 NavigationTarget::from_syntax(file_id, "".into(), None, range, SymbolKind::Field)
347 impl TryToNav for hir::MacroDef {
348 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
349 let src = self.source(db)?;
350 let name_owner: &dyn ast::HasName = match &src.value {
351 Either::Left(it) => it,
352 Either::Right(it) => it,
354 tracing::debug!("nav target {:#?}", name_owner.syntax());
355 let mut res = NavigationTarget::from_named(
357 src.as_ref().with_value(name_owner),
360 res.docs = self.docs(db);
365 impl TryToNav for hir::Adt {
366 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
368 hir::Adt::Struct(it) => it.try_to_nav(db),
369 hir::Adt::Union(it) => it.try_to_nav(db),
370 hir::Adt::Enum(it) => it.try_to_nav(db),
375 impl TryToNav for hir::AssocItem {
376 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
378 AssocItem::Function(it) => it.try_to_nav(db),
379 AssocItem::Const(it) => it.try_to_nav(db),
380 AssocItem::TypeAlias(it) => it.try_to_nav(db),
385 impl TryToNav for hir::GenericParam {
386 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
388 hir::GenericParam::TypeParam(it) => it.try_to_nav(db),
389 hir::GenericParam::ConstParam(it) => it.try_to_nav(db),
390 hir::GenericParam::LifetimeParam(it) => it.try_to_nav(db),
395 impl ToNav for hir::Local {
396 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
397 let InFile { file_id, value } = self.source(db);
398 let (node, name) = match &value {
399 Either::Left(bind_pat) => (bind_pat.syntax(), bind_pat.name()),
400 Either::Right(it) => (it.syntax(), it.name()),
402 let focus_range = name
403 .and_then(|it| InFile::new(file_id, it.syntax()).original_file_range_opt(db))
405 let FileRange { file_id, range: full_range } =
406 InFile::new(file_id, node).original_file_range(db);
408 let name = match self.name(db) {
409 Some(it) => it.to_smol_str(),
412 let kind = if self.is_self(db) {
413 SymbolKind::SelfParam
414 } else if self.is_param(db) {
415 SymbolKind::ValueParam
425 container_name: None,
432 impl ToNav for hir::Label {
433 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
434 let InFile { file_id, value } = self.source(db);
435 let name = self.name(db).to_smol_str();
437 let range = |syntax: &_| InFile::new(file_id, syntax).original_file_range(db);
438 let FileRange { file_id, range: full_range } = range(value.syntax());
439 let focus_range = value.lifetime().map(|lt| range(lt.syntax()).range);
444 kind: Some(SymbolKind::Label),
447 container_name: None,
454 impl TryToNav for hir::TypeParam {
455 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
456 let InFile { file_id, value } = self.source(db)?;
457 let name = self.name(db).to_smol_str();
459 let range = |syntax: &_| InFile::new(file_id, syntax).original_file_range(db);
460 let focus_range = |syntax: &_| InFile::new(file_id, syntax).original_file_range_opt(db);
461 let FileRange { file_id, range: full_range } = match &value {
462 Either::Left(type_param) => range(type_param.syntax()),
463 Either::Right(trait_) => trait_
465 .and_then(|name| focus_range(name.syntax()))
466 .unwrap_or_else(|| range(trait_.syntax())),
468 let focus_range = value
469 .either(|it| it.name(), |it| it.name())
470 .and_then(|it| focus_range(it.syntax()))
472 Some(NavigationTarget {
475 kind: Some(SymbolKind::TypeParam),
478 container_name: None,
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();
490 let FileRange { file_id, range: full_range } =
491 InFile::new(file_id, value.syntax()).original_file_range(db);
492 Some(NavigationTarget {
495 kind: Some(SymbolKind::LifetimeParam),
497 focus_range: Some(full_range),
498 container_name: None,
505 impl TryToNav for hir::ConstParam {
506 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
507 let InFile { file_id, value } = self.source(db)?;
508 let name = self.name(db).to_smol_str();
510 let focus_range = value
512 .and_then(|it| InFile::new(file_id, it.syntax()).original_file_range_opt(db))
514 let FileRange { file_id, range: full_range } =
515 InFile::new(file_id, value.syntax()).original_file_range(db);
516 Some(NavigationTarget {
519 kind: Some(SymbolKind::ConstParam),
522 container_name: None,
529 /// Get a description of a symbol.
531 /// e.g. `struct Name`, `enum Name`, `fn Name`
532 pub(crate) fn description_from_symbol(db: &RootDatabase, symbol: &FileSymbol) -> Option<String> {
533 let sema = Semantics::new(db);
534 let node = symbol.loc.syntax(&sema)?;
538 ast::Fn(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
539 ast::Struct(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
540 ast::Enum(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
541 ast::Trait(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
542 ast::Module(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
543 ast::TypeAlias(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
544 ast::Const(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
545 ast::Static(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
546 ast::RecordField(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
547 ast::Variant(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
548 ast::Union(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
556 use expect_test::expect;
558 use crate::{fixture, Query};
561 fn test_nav_for_symbol() {
562 let (analysis, _) = fixture::file(
565 fn foo() { enum FooInner { } }
569 let navs = analysis.symbol_search(Query::new("FooInner".to_string())).unwrap();
580 description: "enum FooInner",
590 container_name: "foo",
591 description: "enum FooInner",
595 .assert_debug_eq(&navs);
599 fn test_world_symbols_are_case_sensitive() {
600 let (analysis, _) = fixture::file(
607 let navs = analysis.symbol_search(Query::new("foo".to_string())).unwrap();
608 assert_eq!(navs.len(), 2)