1 //! See [`NavigationTarget`].
7 symbols::FileSymbol, AssocItem, Documentation, FieldSource, HasAttrs, HasSource, HirDisplay,
8 InFile, ModuleSource, Semantics,
11 base_db::{FileId, FileRange},
14 use ide_db::{defs::Definition, RootDatabase};
17 match_ast, AstNode, SmolStr, SyntaxNode, TextRange,
20 /// `NavigationTarget` represents an element in the editor's UI which you can
21 /// click on to navigate to a particular piece of code.
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 {
28 /// Range which encompasses the whole element.
30 /// Should include body, doc comments, attributes, etc.
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`.
37 /// Typically, `full_range` is the whole syntax node, including doc
38 /// comments, and `focus_range` is the range of the identifier.
40 /// Clients should place the cursor on this range when navigating to this target.
41 pub focus_range: Option<TextRange>,
43 pub kind: Option<SymbolKind>,
44 pub container_name: Option<SmolStr>,
45 pub description: Option<String>,
46 pub docs: Option<Documentation>,
49 impl fmt::Debug for NavigationTarget {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 let mut f = f.debug_struct("NavigationTarget");
53 ($($name:ident)*) => {$(
54 if let Some(it) = &self.$name {
55 f.field(stringify!($name), it);
59 f.field("file_id", &self.file_id).field("full_range", &self.full_range);
61 f.field("name", &self.name);
62 opt!(kind container_name description docs);
67 pub(crate) trait ToNav {
68 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget;
71 pub(crate) trait TryToNav {
72 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget>;
75 impl<T: TryToNav, U: TryToNav> TryToNav for Either<T, U> {
76 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
78 Either::Left(it) => it.try_to_nav(db),
79 Either::Right(it) => it.try_to_nav(db),
84 impl NavigationTarget {
85 pub fn focus_or_full_range(&self) -> TextRange {
86 self.focus_range.unwrap_or(self.full_range)
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);
94 value.name().and_then(|it| orig_focus_range(db, src.file_id, it.syntax()));
95 let mut res = NavigationTarget::from_syntax(
102 res.docs = module.attrs(db).docs();
103 res.description = Some(module.display(db).to_string());
110 pub(crate) fn debug_render(&self) -> String {
111 let mut buf = format!(
118 if let Some(focus_range) = self.focus_range {
119 buf.push_str(&format!(" {:?}", focus_range))
121 if let Some(container_name) = &self.container_name {
122 buf.push_str(&format!(" {}", container_name))
127 /// Allows `NavigationTarget` to be created from a `NameOwner`
128 pub(crate) fn from_named(
130 node @ InFile { file_id, value }: InFile<&dyn ast::HasName>,
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);
137 NavigationTarget::from_syntax(file_id, name, focus_range, range, kind)
143 focus_range: Option<TextRange>,
144 full_range: TextRange,
146 ) -> NavigationTarget {
153 container_name: None,
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)?;
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),
178 impl TryToNav for Definition {
179 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
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,
202 impl TryToNav for hir::ModuleDef {
203 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
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,
218 pub(crate) trait ToNavFromAst {
219 const KIND: SymbolKind;
221 impl ToNavFromAst for hir::Function {
222 const KIND: SymbolKind = SymbolKind::Function;
224 impl ToNavFromAst for hir::Const {
225 const KIND: SymbolKind = SymbolKind::Const;
227 impl ToNavFromAst for hir::Static {
228 const KIND: SymbolKind = SymbolKind::Static;
230 impl ToNavFromAst for hir::Struct {
231 const KIND: SymbolKind = SymbolKind::Struct;
233 impl ToNavFromAst for hir::Enum {
234 const KIND: SymbolKind = SymbolKind::Enum;
236 impl ToNavFromAst for hir::Variant {
237 const KIND: SymbolKind = SymbolKind::Variant;
239 impl ToNavFromAst for hir::Union {
240 const KIND: SymbolKind = SymbolKind::Union;
242 impl ToNavFromAst for hir::TypeAlias {
243 const KIND: SymbolKind = SymbolKind::TypeAlias;
245 impl ToNavFromAst for hir::Trait {
246 const KIND: SymbolKind = SymbolKind::Trait;
249 impl<D> TryToNav for D
251 D: HasSource + ToNavFromAst + Copy + HasAttrs + HirDisplay,
252 D::Ast: ast::HasName,
254 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
255 let src = self.source(db)?;
256 let mut res = NavigationTarget::from_named(
258 src.as_ref().map(|it| it as &dyn ast::HasName),
261 res.docs = self.docs(db);
262 res.description = Some(self.display(db).to_string());
267 impl ToNav for hir::Module {
268 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
269 let InFile { file_id, value } = self.definition_source(db);
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) => (
276 node.name().and_then(|it| orig_focus_range(db, file_id, it.syntax())),
278 ModuleSource::BlockExpr(node) => (node.syntax(), None),
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)
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);
291 let focus_range = if derive_attr.is_some() {
294 value.self_ty().and_then(|ty| orig_focus_range(db, file_id, ty.syntax()))
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),
302 Some(NavigationTarget::from_syntax(
312 impl TryToNav for hir::Field {
313 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
314 let src = self.source(db)?;
316 let field_source = match &src.value {
317 FieldSource::Named(it) => {
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());
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)
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,
341 tracing::debug!("nav target {:#?}", name_owner.syntax());
342 let mut res = NavigationTarget::from_named(
344 src.as_ref().with_value(name_owner),
347 res.docs = self.docs(db);
352 impl TryToNav for hir::Adt {
353 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
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),
362 impl TryToNav for hir::AssocItem {
363 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
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),
372 impl TryToNav for hir::GenericParam {
373 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
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),
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()),
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);
393 let name = match self.name(db) {
394 Some(it) => it.to_smol_str(),
397 let kind = if self.is_self(db) {
398 SymbolKind::SelfParam
399 } else if self.is_param(db) {
400 SymbolKind::ValueParam
410 container_name: None,
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();
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);
429 kind: Some(SymbolKind::Label),
432 container_name: None,
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();
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_
450 .and_then(|name| focus_range(name.syntax()))
451 .unwrap_or_else(|| range(trait_.syntax())),
453 let focus_range = value
454 .either(|it| it.name(), |it| it.name())
455 .and_then(|it| focus_range(it.syntax()))
457 Some(NavigationTarget {
460 kind: Some(SymbolKind::TypeParam),
463 container_name: None,
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();
475 let FileRange { file_id, range: full_range } =
476 InFile::new(file_id, value.syntax()).original_file_range(db);
477 Some(NavigationTarget {
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 InFile { file_id, value } = self.source(db)?;
493 let name = self.name(db).to_smol_str();
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 {
501 kind: Some(SymbolKind::ConstParam),
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 node = symbol.loc.syntax(&sema)?;
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()),
538 file_id: hir::HirFileId,
540 ) -> Option<TextRange> {
541 InFile::new(file_id, syntax).original_file_range_opt(db).map(|it| it.range)
546 use expect_test::expect;
548 use crate::{fixture, Query};
551 fn test_nav_for_symbol() {
552 let (analysis, _) = fixture::file(
555 fn foo() { enum FooInner { } }
559 let navs = analysis.symbol_search(Query::new("FooInner".to_string())).unwrap();
570 description: "enum FooInner",
580 container_name: "foo",
581 description: "enum FooInner",
585 .assert_debug_eq(&navs);
589 fn test_world_symbols_are_case_sensitive() {
590 let (analysis, _) = fixture::file(
597 let navs = analysis.symbol_search(Query::new("foo".to_string())).unwrap();
598 assert_eq!(navs.len(), 2)