1 //! See [`NavigationTarget`].
7 AssocItem, Documentation, FieldSource, HasAttrs, HasSource, HirDisplay, InFile, ModuleSource,
11 base_db::{FileId, FileRange},
12 symbol_index::FileSymbolKind,
15 use ide_db::{defs::Definition, RootDatabase};
17 ast::{self, NameOwner},
18 match_ast, AstNode, SmolStr, TextRange,
21 use crate::FileSymbol;
23 /// `NavigationTarget` represents an element in the editor's UI which you can
24 /// click on to navigate to a particular piece of code.
26 /// Typically, a `NavigationTarget` corresponds to some element in the source
27 /// code, like a function or a struct, but this is not strictly required.
28 #[derive(Clone, PartialEq, Eq, Hash)]
29 pub struct NavigationTarget {
31 /// Range which encompasses the whole element.
33 /// Should include body, doc comments, attributes, etc.
35 /// Clients should use this range to answer "is the cursor inside the
36 /// element?" question.
37 pub full_range: TextRange,
38 /// A "most interesting" range within the `full_range`.
40 /// Typically, `full_range` is the whole syntax node, including doc
41 /// comments, and `focus_range` is the range of the identifier.
43 /// Clients should place the cursor on this range when navigating to this target.
44 pub focus_range: Option<TextRange>,
46 pub kind: Option<SymbolKind>,
47 pub container_name: Option<SmolStr>,
48 pub description: Option<String>,
49 pub docs: Option<Documentation>,
52 impl fmt::Debug for NavigationTarget {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 let mut f = f.debug_struct("NavigationTarget");
56 ($($name:ident)*) => {$(
57 if let Some(it) = &self.$name {
58 f.field(stringify!($name), it);
62 f.field("file_id", &self.file_id).field("full_range", &self.full_range);
64 f.field("name", &self.name);
65 opt!(kind container_name description docs);
70 pub(crate) trait ToNav {
71 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget;
74 pub(crate) trait TryToNav {
75 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget>;
78 impl NavigationTarget {
79 pub fn focus_or_full_range(&self) -> TextRange {
80 self.focus_range.unwrap_or(self.full_range)
83 pub(crate) fn from_module_to_decl(db: &RootDatabase, module: hir::Module) -> NavigationTarget {
84 let name = module.name(db).map(|it| it.to_string().into()).unwrap_or_default();
85 if let Some(src) = module.declaration_source(db) {
86 let node = src.as_ref().map(|it| it.syntax());
87 let full_range = node.original_file_range(db);
91 .map(|name| src.with_value(name.syntax()).original_file_range(db).range);
92 let mut res = NavigationTarget::from_syntax(
99 res.docs = module.attrs(db).docs();
100 res.description = Some(module.display(db).to_string());
107 pub(crate) fn assert_match(&self, expected: &str) {
108 let actual = self.debug_render();
109 test_utils::assert_eq_text!(expected.trim(), actual.trim(),);
113 pub(crate) fn debug_render(&self) -> String {
114 let mut buf = format!(
121 if let Some(focus_range) = self.focus_range {
122 buf.push_str(&format!(" {:?}", focus_range))
124 if let Some(container_name) = &self.container_name {
125 buf.push_str(&format!(" {}", container_name))
130 /// Allows `NavigationTarget` to be created from a `NameOwner`
131 pub(crate) fn from_named(
133 node: InFile<&dyn ast::NameOwner>,
135 ) -> NavigationTarget {
136 let name = node.value.name().map(|it| it.text().into()).unwrap_or_else(|| "_".into());
138 node.value.name().map(|it| node.with_value(it.syntax()).original_file_range(db).range);
139 let frange = node.map(|it| it.syntax()).original_file_range(db);
141 NavigationTarget::from_syntax(frange.file_id, name, focus_range, frange.range, kind)
147 focus_range: Option<TextRange>,
148 full_range: TextRange,
150 ) -> NavigationTarget {
157 container_name: None,
164 impl ToNav for FileSymbol {
165 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
167 file_id: self.file_id,
168 name: self.name.clone(),
169 kind: Some(match self.kind {
170 FileSymbolKind::Function => SymbolKind::Function,
171 FileSymbolKind::Struct => SymbolKind::Struct,
172 FileSymbolKind::Enum => SymbolKind::Enum,
173 FileSymbolKind::Trait => SymbolKind::Trait,
174 FileSymbolKind::Module => SymbolKind::Module,
175 FileSymbolKind::TypeAlias => SymbolKind::TypeAlias,
176 FileSymbolKind::Const => SymbolKind::Const,
177 FileSymbolKind::Static => SymbolKind::Static,
178 FileSymbolKind::Macro => SymbolKind::Macro,
179 FileSymbolKind::Union => SymbolKind::Union,
181 full_range: self.range,
182 focus_range: self.name_range,
183 container_name: self.container_name.clone(),
184 description: description_from_symbol(db, self),
190 impl TryToNav for Definition {
191 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
193 Definition::Macro(it) => it.try_to_nav(db),
194 Definition::Field(it) => it.try_to_nav(db),
195 Definition::ModuleDef(it) => it.try_to_nav(db),
196 Definition::SelfType(it) => it.try_to_nav(db),
197 Definition::Local(it) => Some(it.to_nav(db)),
198 Definition::GenericParam(it) => it.try_to_nav(db),
199 Definition::Label(it) => Some(it.to_nav(db)),
204 impl TryToNav for hir::ModuleDef {
205 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
207 hir::ModuleDef::Module(it) => Some(it.to_nav(db)),
208 hir::ModuleDef::Function(it) => it.try_to_nav(db),
209 hir::ModuleDef::Adt(it) => it.try_to_nav(db),
210 hir::ModuleDef::Variant(it) => it.try_to_nav(db),
211 hir::ModuleDef::Const(it) => it.try_to_nav(db),
212 hir::ModuleDef::Static(it) => it.try_to_nav(db),
213 hir::ModuleDef::Trait(it) => it.try_to_nav(db),
214 hir::ModuleDef::TypeAlias(it) => it.try_to_nav(db),
215 hir::ModuleDef::BuiltinType(_) => None,
220 pub(crate) trait ToNavFromAst {
221 const KIND: SymbolKind;
223 impl ToNavFromAst for hir::Function {
224 const KIND: SymbolKind = SymbolKind::Function;
226 impl ToNavFromAst for hir::Const {
227 const KIND: SymbolKind = SymbolKind::Const;
229 impl ToNavFromAst for hir::Static {
230 const KIND: SymbolKind = SymbolKind::Static;
232 impl ToNavFromAst for hir::Struct {
233 const KIND: SymbolKind = SymbolKind::Struct;
235 impl ToNavFromAst for hir::Enum {
236 const KIND: SymbolKind = SymbolKind::Enum;
238 impl ToNavFromAst for hir::Variant {
239 const KIND: SymbolKind = SymbolKind::Variant;
241 impl ToNavFromAst for hir::Union {
242 const KIND: SymbolKind = SymbolKind::Union;
244 impl ToNavFromAst for hir::TypeAlias {
245 const KIND: SymbolKind = SymbolKind::TypeAlias;
247 impl ToNavFromAst for hir::Trait {
248 const KIND: SymbolKind = SymbolKind::Trait;
251 impl<D> TryToNav for D
253 D: HasSource + ToNavFromAst + Copy + HasAttrs + HirDisplay,
254 D::Ast: ast::NameOwner,
256 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
257 let src = self.source(db)?;
258 let mut res = NavigationTarget::from_named(
260 src.as_ref().map(|it| it as &dyn ast::NameOwner),
263 res.docs = self.docs(db);
264 res.description = Some(self.display(db).to_string());
269 impl ToNav for hir::Module {
270 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
271 let src = self.definition_source(db);
272 let name = self.name(db).map(|it| it.to_string().into()).unwrap_or_default();
273 let (syntax, focus) = match &src.value {
274 ModuleSource::SourceFile(node) => (node.syntax(), None),
275 ModuleSource::Module(node) => {
276 (node.syntax(), node.name().map(|it| it.syntax().text_range()))
278 ModuleSource::BlockExpr(node) => (node.syntax(), None),
280 let frange = src.with_value(syntax).original_file_range(db);
281 NavigationTarget::from_syntax(frange.file_id, name, focus, frange.range, SymbolKind::Module)
285 impl TryToNav for hir::Impl {
286 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
287 let src = self.source(db)?;
288 let derive_attr = self.is_builtin_derive(db);
289 let frange = if let Some(item) = &derive_attr {
290 item.syntax().original_file_range(db)
292 src.as_ref().map(|it| it.syntax()).original_file_range(db)
294 let focus_range = if derive_attr.is_some() {
297 src.value.self_ty().map(|ty| src.with_value(ty.syntax()).original_file_range(db).range)
300 Some(NavigationTarget::from_syntax(
310 impl TryToNav for hir::Field {
311 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
312 let src = self.source(db)?;
314 let field_source = match &src.value {
315 FieldSource::Named(it) => {
317 NavigationTarget::from_named(db, src.with_value(it), SymbolKind::Field);
318 res.docs = self.docs(db);
319 res.description = Some(self.display(db).to_string());
322 FieldSource::Pos(it) => {
323 let frange = src.with_value(it.syntax()).original_file_range(db);
324 NavigationTarget::from_syntax(
337 impl TryToNav for hir::MacroDef {
338 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
339 let src = self.source(db)?;
340 let name_owner: &dyn ast::NameOwner = match &src.value {
341 Either::Left(it) => it,
342 Either::Right(it) => it,
344 log::debug!("nav target {:#?}", name_owner.syntax());
345 let mut res = NavigationTarget::from_named(
347 src.as_ref().with_value(name_owner),
350 res.docs = self.docs(db);
355 impl TryToNav for hir::Adt {
356 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
358 hir::Adt::Struct(it) => it.try_to_nav(db),
359 hir::Adt::Union(it) => it.try_to_nav(db),
360 hir::Adt::Enum(it) => it.try_to_nav(db),
365 impl TryToNav for hir::AssocItem {
366 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
368 AssocItem::Function(it) => it.try_to_nav(db),
369 AssocItem::Const(it) => it.try_to_nav(db),
370 AssocItem::TypeAlias(it) => it.try_to_nav(db),
375 impl TryToNav for hir::GenericParam {
376 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
378 hir::GenericParam::TypeParam(it) => it.try_to_nav(db),
379 hir::GenericParam::ConstParam(it) => it.try_to_nav(db),
380 hir::GenericParam::LifetimeParam(it) => it.try_to_nav(db),
385 impl ToNav for hir::Local {
386 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
387 let src = self.source(db);
388 let (node, name) = match &src.value {
389 Either::Left(bind_pat) => (bind_pat.syntax().clone(), bind_pat.name()),
390 Either::Right(it) => (it.syntax().clone(), it.name()),
393 name.map(|it| src.with_value(&it.syntax().clone()).original_file_range(db).range);
395 let full_range = src.with_value(&node).original_file_range(db);
396 let name = match self.name(db) {
397 Some(it) => it.to_string().into(),
400 let kind = if self.is_self(db) {
401 SymbolKind::SelfParam
402 } else if self.is_param(db) {
403 SymbolKind::ValueParam
408 file_id: full_range.file_id,
411 full_range: full_range.range,
413 container_name: None,
420 impl ToNav for hir::Label {
421 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
422 let src = self.source(db);
423 let node = src.value.syntax();
424 let FileRange { file_id, range } = src.with_value(node).original_file_range(db);
426 src.value.lifetime().and_then(|lt| lt.lifetime_ident_token()).map(|lt| lt.text_range());
427 let name = self.name(db).to_string().into();
431 kind: Some(SymbolKind::Label),
434 container_name: None,
441 impl TryToNav for hir::TypeParam {
442 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
443 let src = self.source(db)?;
444 let full_range = match &src.value {
445 Either::Left(it) => it
447 .map_or_else(|| it.syntax().text_range(), |name| name.syntax().text_range()),
448 Either::Right(it) => it.syntax().text_range(),
450 let focus_range = match &src.value {
451 Either::Left(it) => it.name(),
452 Either::Right(it) => it.name(),
454 .map(|it| it.syntax().text_range());
455 Some(NavigationTarget {
456 file_id: src.file_id.original_file(db),
457 name: self.name(db).to_string().into(),
458 kind: Some(SymbolKind::TypeParam),
461 container_name: None,
468 impl TryToNav for hir::LifetimeParam {
469 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
470 let src = self.source(db)?;
471 let full_range = src.value.syntax().text_range();
472 Some(NavigationTarget {
473 file_id: src.file_id.original_file(db),
474 name: self.name(db).to_string().into(),
475 kind: Some(SymbolKind::LifetimeParam),
477 focus_range: Some(full_range),
478 container_name: None,
485 impl TryToNav for hir::ConstParam {
486 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
487 let src = self.source(db)?;
488 let full_range = src.value.syntax().text_range();
489 Some(NavigationTarget {
490 file_id: src.file_id.original_file(db),
491 name: self.name(db).to_string().into(),
492 kind: Some(SymbolKind::ConstParam),
494 focus_range: src.value.name().map(|n| n.syntax().text_range()),
495 container_name: None,
502 /// Get a description of a symbol.
504 /// e.g. `struct Name`, `enum Name`, `fn Name`
505 pub(crate) fn description_from_symbol(db: &RootDatabase, symbol: &FileSymbol) -> Option<String> {
506 let sema = Semantics::new(db);
507 let parse = sema.parse(symbol.file_id);
508 let node = symbol.ptr.to_node(parse.syntax());
512 ast::Fn(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
513 ast::Struct(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
514 ast::Enum(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
515 ast::Trait(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
516 ast::Module(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
517 ast::TypeAlias(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
518 ast::Const(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
519 ast::Static(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
520 ast::RecordField(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
521 ast::Variant(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
529 use expect_test::expect;
531 use crate::{fixture, Query};
534 fn test_nav_for_symbol() {
535 let (analysis, _) = fixture::file(
538 fn foo() { enum FooInner { } }
542 let navs = analysis.symbol_search(Query::new("FooInner".to_string())).unwrap();
553 description: "enum FooInner",
563 container_name: "foo",
564 description: "enum FooInner",
568 .assert_debug_eq(&navs);
572 fn test_world_symbols_are_case_sensitive() {
573 let (analysis, _) = fixture::file(
580 let navs = analysis.symbol_search(Query::new("foo".to_string())).unwrap();
581 assert_eq!(navs.len(), 2)