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<T: TryToNav, U: TryToNav> TryToNav for Either<T, U> {
79 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
81 Either::Left(it) => it.try_to_nav(db),
82 Either::Right(it) => it.try_to_nav(db),
87 impl NavigationTarget {
88 pub fn focus_or_full_range(&self) -> TextRange {
89 self.focus_range.unwrap_or(self.full_range)
92 pub(crate) fn from_module_to_decl(db: &RootDatabase, module: hir::Module) -> NavigationTarget {
93 let name = module.name(db).map(|it| it.to_string().into()).unwrap_or_default();
94 if let Some(src) = module.declaration_source(db) {
95 let node = src.as_ref().map(|it| it.syntax());
96 let full_range = node.original_file_range(db);
100 .map(|name| src.with_value(name.syntax()).original_file_range(db).range);
101 let mut res = NavigationTarget::from_syntax(
108 res.docs = module.attrs(db).docs();
109 res.description = Some(module.display(db).to_string());
116 pub(crate) fn assert_match(&self, expected: &str) {
117 let actual = self.debug_render();
118 test_utils::assert_eq_text!(expected.trim(), actual.trim(),);
122 pub(crate) fn debug_render(&self) -> String {
123 let mut buf = format!(
130 if let Some(focus_range) = self.focus_range {
131 buf.push_str(&format!(" {:?}", focus_range))
133 if let Some(container_name) = &self.container_name {
134 buf.push_str(&format!(" {}", container_name))
139 /// Allows `NavigationTarget` to be created from a `NameOwner`
140 pub(crate) fn from_named(
142 node: InFile<&dyn ast::NameOwner>,
144 ) -> NavigationTarget {
145 let name = node.value.name().map(|it| it.text().into()).unwrap_or_else(|| "_".into());
147 node.value.name().map(|it| node.with_value(it.syntax()).original_file_range(db).range);
148 let frange = node.map(|it| it.syntax()).original_file_range(db);
150 NavigationTarget::from_syntax(frange.file_id, name, focus_range, frange.range, kind)
156 focus_range: Option<TextRange>,
157 full_range: TextRange,
159 ) -> NavigationTarget {
166 container_name: None,
173 impl ToNav for FileSymbol {
174 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
176 file_id: self.file_id,
177 name: self.name.clone(),
178 kind: Some(match self.kind {
179 FileSymbolKind::Function => SymbolKind::Function,
180 FileSymbolKind::Struct => SymbolKind::Struct,
181 FileSymbolKind::Enum => SymbolKind::Enum,
182 FileSymbolKind::Trait => SymbolKind::Trait,
183 FileSymbolKind::Module => SymbolKind::Module,
184 FileSymbolKind::TypeAlias => SymbolKind::TypeAlias,
185 FileSymbolKind::Const => SymbolKind::Const,
186 FileSymbolKind::Static => SymbolKind::Static,
187 FileSymbolKind::Macro => SymbolKind::Macro,
188 FileSymbolKind::Union => SymbolKind::Union,
190 full_range: self.range,
191 focus_range: self.name_range,
192 container_name: self.container_name.clone(),
193 description: description_from_symbol(db, self),
199 impl TryToNav for Definition {
200 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
202 Definition::Macro(it) => it.try_to_nav(db),
203 Definition::Field(it) => it.try_to_nav(db),
204 Definition::ModuleDef(it) => it.try_to_nav(db),
205 Definition::SelfType(it) => it.try_to_nav(db),
206 Definition::Local(it) => Some(it.to_nav(db)),
207 Definition::GenericParam(it) => it.try_to_nav(db),
208 Definition::Label(it) => Some(it.to_nav(db)),
213 impl TryToNav for hir::ModuleDef {
214 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
216 hir::ModuleDef::Module(it) => Some(it.to_nav(db)),
217 hir::ModuleDef::Function(it) => it.try_to_nav(db),
218 hir::ModuleDef::Adt(it) => it.try_to_nav(db),
219 hir::ModuleDef::Variant(it) => it.try_to_nav(db),
220 hir::ModuleDef::Const(it) => it.try_to_nav(db),
221 hir::ModuleDef::Static(it) => it.try_to_nav(db),
222 hir::ModuleDef::Trait(it) => it.try_to_nav(db),
223 hir::ModuleDef::TypeAlias(it) => it.try_to_nav(db),
224 hir::ModuleDef::BuiltinType(_) => None,
229 pub(crate) trait ToNavFromAst {
230 const KIND: SymbolKind;
232 impl ToNavFromAst for hir::Function {
233 const KIND: SymbolKind = SymbolKind::Function;
235 impl ToNavFromAst for hir::Const {
236 const KIND: SymbolKind = SymbolKind::Const;
238 impl ToNavFromAst for hir::Static {
239 const KIND: SymbolKind = SymbolKind::Static;
241 impl ToNavFromAst for hir::Struct {
242 const KIND: SymbolKind = SymbolKind::Struct;
244 impl ToNavFromAst for hir::Enum {
245 const KIND: SymbolKind = SymbolKind::Enum;
247 impl ToNavFromAst for hir::Variant {
248 const KIND: SymbolKind = SymbolKind::Variant;
250 impl ToNavFromAst for hir::Union {
251 const KIND: SymbolKind = SymbolKind::Union;
253 impl ToNavFromAst for hir::TypeAlias {
254 const KIND: SymbolKind = SymbolKind::TypeAlias;
256 impl ToNavFromAst for hir::Trait {
257 const KIND: SymbolKind = SymbolKind::Trait;
260 impl<D> TryToNav for D
262 D: HasSource + ToNavFromAst + Copy + HasAttrs + HirDisplay,
263 D::Ast: ast::NameOwner,
265 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
266 let src = self.source(db)?;
267 let mut res = NavigationTarget::from_named(
269 src.as_ref().map(|it| it as &dyn ast::NameOwner),
272 res.docs = self.docs(db);
273 res.description = Some(self.display(db).to_string());
278 impl ToNav for hir::Module {
279 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
280 let src = self.definition_source(db);
281 let name = self.name(db).map(|it| it.to_string().into()).unwrap_or_default();
282 let (syntax, focus) = match &src.value {
283 ModuleSource::SourceFile(node) => (node.syntax(), None),
284 ModuleSource::Module(node) => {
285 (node.syntax(), node.name().map(|it| it.syntax().text_range()))
287 ModuleSource::BlockExpr(node) => (node.syntax(), None),
289 let frange = src.with_value(syntax).original_file_range(db);
290 NavigationTarget::from_syntax(frange.file_id, name, focus, frange.range, SymbolKind::Module)
294 impl TryToNav for hir::Impl {
295 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
296 let src = self.source(db)?;
297 let derive_attr = self.is_builtin_derive(db);
298 let frange = if let Some(item) = &derive_attr {
299 item.syntax().original_file_range(db)
301 src.as_ref().map(|it| it.syntax()).original_file_range(db)
303 let focus_range = if derive_attr.is_some() {
306 src.value.self_ty().map(|ty| src.with_value(ty.syntax()).original_file_range(db).range)
309 Some(NavigationTarget::from_syntax(
319 impl TryToNav for hir::Field {
320 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
321 let src = self.source(db)?;
323 let field_source = match &src.value {
324 FieldSource::Named(it) => {
326 NavigationTarget::from_named(db, src.with_value(it), SymbolKind::Field);
327 res.docs = self.docs(db);
328 res.description = Some(self.display(db).to_string());
331 FieldSource::Pos(it) => {
332 let frange = src.with_value(it.syntax()).original_file_range(db);
333 NavigationTarget::from_syntax(
346 impl TryToNav for hir::MacroDef {
347 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
348 let src = self.source(db)?;
349 let name_owner: &dyn ast::NameOwner = match &src.value {
350 Either::Left(it) => it,
351 Either::Right(it) => it,
353 log::debug!("nav target {:#?}", name_owner.syntax());
354 let mut res = NavigationTarget::from_named(
356 src.as_ref().with_value(name_owner),
359 res.docs = self.docs(db);
364 impl TryToNav for hir::Adt {
365 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
367 hir::Adt::Struct(it) => it.try_to_nav(db),
368 hir::Adt::Union(it) => it.try_to_nav(db),
369 hir::Adt::Enum(it) => it.try_to_nav(db),
374 impl TryToNav for hir::AssocItem {
375 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
377 AssocItem::Function(it) => it.try_to_nav(db),
378 AssocItem::Const(it) => it.try_to_nav(db),
379 AssocItem::TypeAlias(it) => it.try_to_nav(db),
384 impl TryToNav for hir::GenericParam {
385 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
387 hir::GenericParam::TypeParam(it) => it.try_to_nav(db),
388 hir::GenericParam::ConstParam(it) => it.try_to_nav(db),
389 hir::GenericParam::LifetimeParam(it) => it.try_to_nav(db),
394 impl ToNav for hir::Local {
395 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
396 let src = self.source(db);
397 let (node, name) = match &src.value {
398 Either::Left(bind_pat) => (bind_pat.syntax().clone(), bind_pat.name()),
399 Either::Right(it) => (it.syntax().clone(), it.name()),
402 name.map(|it| src.with_value(&it.syntax().clone()).original_file_range(db).range);
404 let full_range = src.with_value(&node).original_file_range(db);
405 let name = match self.name(db) {
406 Some(it) => it.to_string().into(),
409 let kind = if self.is_self(db) {
410 SymbolKind::SelfParam
411 } else if self.is_param(db) {
412 SymbolKind::ValueParam
417 file_id: full_range.file_id,
420 full_range: full_range.range,
422 container_name: None,
429 impl ToNav for hir::Label {
430 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
431 let src = self.source(db);
432 let node = src.value.syntax();
433 let FileRange { file_id, range } = src.with_value(node).original_file_range(db);
435 src.value.lifetime().and_then(|lt| lt.lifetime_ident_token()).map(|lt| lt.text_range());
436 let name = self.name(db).to_string().into();
440 kind: Some(SymbolKind::Label),
443 container_name: None,
450 impl TryToNav for hir::TypeParam {
451 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
452 let src = self.source(db)?;
453 let full_range = match &src.value {
454 Either::Left(type_param) => type_param.syntax().text_range(),
455 Either::Right(trait_) => trait_
457 .map_or_else(|| trait_.syntax().text_range(), |name| name.syntax().text_range()),
459 let focus_range = match &src.value {
460 Either::Left(it) => it.name(),
461 Either::Right(it) => it.name(),
463 .map(|it| it.syntax().text_range());
464 Some(NavigationTarget {
465 file_id: src.file_id.original_file(db),
466 name: self.name(db).to_string().into(),
467 kind: Some(SymbolKind::TypeParam),
470 container_name: None,
477 impl TryToNav for hir::LifetimeParam {
478 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
479 let src = self.source(db)?;
480 let full_range = src.value.syntax().text_range();
481 Some(NavigationTarget {
482 file_id: src.file_id.original_file(db),
483 name: self.name(db).to_string().into(),
484 kind: Some(SymbolKind::LifetimeParam),
486 focus_range: Some(full_range),
487 container_name: None,
494 impl TryToNav for hir::ConstParam {
495 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
496 let src = self.source(db)?;
497 let full_range = src.value.syntax().text_range();
498 Some(NavigationTarget {
499 file_id: src.file_id.original_file(db),
500 name: self.name(db).to_string().into(),
501 kind: Some(SymbolKind::ConstParam),
503 focus_range: src.value.name().map(|n| n.syntax().text_range()),
504 container_name: None,
511 /// Get a description of a symbol.
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 parse = sema.parse(symbol.file_id);
517 let node = symbol.ptr.to_node(parse.syntax());
521 ast::Fn(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
522 ast::Struct(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
523 ast::Enum(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
524 ast::Trait(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
525 ast::Module(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
526 ast::TypeAlias(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
527 ast::Const(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
528 ast::Static(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
529 ast::RecordField(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
530 ast::Variant(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
531 ast::Union(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
539 use expect_test::expect;
541 use crate::{fixture, Query};
544 fn test_nav_for_symbol() {
545 let (analysis, _) = fixture::file(
548 fn foo() { enum FooInner { } }
552 let navs = analysis.symbol_search(Query::new("FooInner".to_string())).unwrap();
563 description: "enum FooInner",
573 container_name: "foo",
574 description: "enum FooInner",
578 .assert_debug_eq(&navs);
582 fn test_world_symbols_are_case_sensitive() {
583 let (analysis, _) = fixture::file(
590 let navs = analysis.symbol_search(Query::new("foo".to_string())).unwrap();
591 assert_eq!(navs.len(), 2)