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};
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.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 debug_render(&self) -> String {
117 let mut buf = format!(
124 if let Some(focus_range) = self.focus_range {
125 buf.push_str(&format!(" {:?}", focus_range))
127 if let Some(container_name) = &self.container_name {
128 buf.push_str(&format!(" {}", container_name))
133 /// Allows `NavigationTarget` to be created from a `NameOwner`
134 pub(crate) fn from_named(
136 node: InFile<&dyn ast::HasName>,
138 ) -> NavigationTarget {
139 let name = node.value.name().map(|it| it.text().into()).unwrap_or_else(|| "_".into());
140 let focus_range = node
143 .and_then(|it| node.with_value(it.syntax()).original_file_range_opt(db))
145 let frange = node.map(|it| it.syntax()).original_file_range(db);
147 NavigationTarget::from_syntax(frange.file_id, name, focus_range, frange.range, kind)
153 focus_range: Option<TextRange>,
154 full_range: TextRange,
156 ) -> NavigationTarget {
163 container_name: None,
170 impl ToNav for FileSymbol {
171 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
173 file_id: self.file_id,
174 name: self.name.clone(),
175 kind: Some(match self.kind {
176 FileSymbolKind::Function => SymbolKind::Function,
177 FileSymbolKind::Struct => SymbolKind::Struct,
178 FileSymbolKind::Enum => SymbolKind::Enum,
179 FileSymbolKind::Trait => SymbolKind::Trait,
180 FileSymbolKind::Module => SymbolKind::Module,
181 FileSymbolKind::TypeAlias => SymbolKind::TypeAlias,
182 FileSymbolKind::Const => SymbolKind::Const,
183 FileSymbolKind::Static => SymbolKind::Static,
184 FileSymbolKind::Macro => SymbolKind::Macro,
185 FileSymbolKind::Union => SymbolKind::Union,
187 full_range: self.range,
188 focus_range: self.name_range,
189 container_name: self.container_name.clone(),
190 description: description_from_symbol(db, self),
196 impl TryToNav for Definition {
197 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
199 Definition::Macro(it) => it.try_to_nav(db),
200 Definition::Field(it) => it.try_to_nav(db),
201 Definition::ModuleDef(it) => it.try_to_nav(db),
202 Definition::SelfType(it) => it.try_to_nav(db),
203 Definition::Local(it) => Some(it.to_nav(db)),
204 Definition::GenericParam(it) => it.try_to_nav(db),
205 Definition::Label(it) => Some(it.to_nav(db)),
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 src = self.definition_source(db);
278 let name = self.name(db).map(|it| it.to_string().into()).unwrap_or_default();
279 let (syntax, focus) = match &src.value {
280 ModuleSource::SourceFile(node) => (node.syntax(), None),
281 ModuleSource::Module(node) => {
282 (node.syntax(), node.name().map(|it| it.syntax().text_range()))
284 ModuleSource::BlockExpr(node) => (node.syntax(), None),
286 let frange = src.with_value(syntax).original_file_range(db);
287 NavigationTarget::from_syntax(frange.file_id, name, focus, frange.range, SymbolKind::Module)
291 impl TryToNav for hir::Impl {
292 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
293 let src = self.source(db)?;
294 let derive_attr = self.is_builtin_derive(db);
295 let frange = match &derive_attr {
296 Some(item) => item.syntax().original_file_range(db),
297 None => src.syntax().original_file_range(db),
299 let focus_range = if derive_attr.is_some() {
302 src.value.self_ty().map(|ty| src.with_value(ty.syntax()).original_file_range(db).range)
305 Some(NavigationTarget::from_syntax(
315 impl TryToNav for hir::Field {
316 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
317 let src = self.source(db)?;
319 let field_source = match &src.value {
320 FieldSource::Named(it) => {
322 NavigationTarget::from_named(db, src.with_value(it), SymbolKind::Field);
323 res.docs = self.docs(db);
324 res.description = Some(self.display(db).to_string());
327 FieldSource::Pos(it) => {
328 let frange = src.with_value(it.syntax()).original_file_range(db);
329 NavigationTarget::from_syntax(
342 impl TryToNav for hir::MacroDef {
343 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
344 let src = self.source(db)?;
345 let name_owner: &dyn ast::HasName = match &src.value {
346 Either::Left(it) => it,
347 Either::Right(it) => it,
349 tracing::debug!("nav target {:#?}", name_owner.syntax());
350 let mut res = NavigationTarget::from_named(
352 src.as_ref().with_value(name_owner),
355 res.docs = self.docs(db);
360 impl TryToNav for hir::Adt {
361 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
363 hir::Adt::Struct(it) => it.try_to_nav(db),
364 hir::Adt::Union(it) => it.try_to_nav(db),
365 hir::Adt::Enum(it) => it.try_to_nav(db),
370 impl TryToNav for hir::AssocItem {
371 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
373 AssocItem::Function(it) => it.try_to_nav(db),
374 AssocItem::Const(it) => it.try_to_nav(db),
375 AssocItem::TypeAlias(it) => it.try_to_nav(db),
380 impl TryToNav for hir::GenericParam {
381 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
383 hir::GenericParam::TypeParam(it) => it.try_to_nav(db),
384 hir::GenericParam::ConstParam(it) => it.try_to_nav(db),
385 hir::GenericParam::LifetimeParam(it) => it.try_to_nav(db),
390 impl ToNav for hir::Local {
391 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
392 let src = self.source(db);
393 let (node, name) = match &src.value {
394 Either::Left(bind_pat) => (bind_pat.syntax().clone(), bind_pat.name()),
395 Either::Right(it) => (it.syntax().clone(), it.name()),
398 name.map(|it| src.with_value(&it.syntax().clone()).original_file_range(db).range);
400 let full_range = src.with_value(&node).original_file_range(db);
401 let name = match self.name(db) {
402 Some(it) => it.to_string().into(),
405 let kind = if self.is_self(db) {
406 SymbolKind::SelfParam
407 } else if self.is_param(db) {
408 SymbolKind::ValueParam
413 file_id: full_range.file_id,
416 full_range: full_range.range,
418 container_name: None,
425 impl ToNav for hir::Label {
426 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
427 let src = self.source(db);
428 let node = src.value.syntax();
429 let FileRange { file_id, range } = src.with_value(node).original_file_range(db);
431 src.value.lifetime().and_then(|lt| lt.lifetime_ident_token()).map(|lt| lt.text_range());
432 let name = self.name(db).to_string().into();
436 kind: Some(SymbolKind::Label),
439 container_name: None,
446 impl TryToNav for hir::TypeParam {
447 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
448 let src = self.source(db)?;
449 let full_range = match &src.value {
450 Either::Left(type_param) => type_param.syntax().text_range(),
451 Either::Right(trait_) => trait_
453 .map_or_else(|| trait_.syntax().text_range(), |name| name.syntax().text_range()),
455 let focus_range = match &src.value {
456 Either::Left(it) => it.name(),
457 Either::Right(it) => it.name(),
459 .map(|it| it.syntax().text_range());
460 Some(NavigationTarget {
461 file_id: src.file_id.original_file(db),
462 name: self.name(db).to_string().into(),
463 kind: Some(SymbolKind::TypeParam),
466 container_name: None,
473 impl TryToNav for hir::LifetimeParam {
474 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
475 let src = self.source(db)?;
476 let full_range = src.value.syntax().text_range();
477 Some(NavigationTarget {
478 file_id: src.file_id.original_file(db),
479 name: self.name(db).to_string().into(),
480 kind: Some(SymbolKind::LifetimeParam),
482 focus_range: Some(full_range),
483 container_name: None,
490 impl TryToNav for hir::ConstParam {
491 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
492 let src = self.source(db)?;
493 let full_range = src.value.syntax().text_range();
494 Some(NavigationTarget {
495 file_id: src.file_id.original_file(db),
496 name: self.name(db).to_string().into(),
497 kind: Some(SymbolKind::ConstParam),
499 focus_range: src.value.name().map(|n| n.syntax().text_range()),
500 container_name: None,
507 /// Get a description of a symbol.
509 /// e.g. `struct Name`, `enum Name`, `fn Name`
510 pub(crate) fn description_from_symbol(db: &RootDatabase, symbol: &FileSymbol) -> Option<String> {
511 let sema = Semantics::new(db);
512 let parse = sema.parse(symbol.file_id);
513 let node = symbol.ptr.to_node(parse.syntax());
517 ast::Fn(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
518 ast::Struct(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
519 ast::Enum(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
520 ast::Trait(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
521 ast::Module(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
522 ast::TypeAlias(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
523 ast::Const(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
524 ast::Static(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
525 ast::RecordField(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
526 ast::Variant(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
527 ast::Union(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
535 use expect_test::expect;
537 use crate::{fixture, Query};
540 fn test_nav_for_symbol() {
541 let (analysis, _) = fixture::file(
544 fn foo() { enum FooInner { } }
548 let navs = analysis.symbol_search(Query::new("FooInner".to_string())).unwrap();
559 description: "enum FooInner",
569 container_name: "foo",
570 description: "enum FooInner",
574 .assert_debug_eq(&navs);
578 fn test_world_symbols_are_case_sensitive() {
579 let (analysis, _) = fixture::file(
586 let navs = analysis.symbol_search(Query::new("foo".to_string())).unwrap();
587 assert_eq!(navs.len(), 2)