1 //! FIXME: write short doc here
6 use hir::{AssocItem, Documentation, FieldSource, HasAttrs, HasSource, InFile, ModuleSource};
8 base_db::{FileId, FileRange, SourceDatabase},
9 symbol_index::FileSymbolKind,
11 use ide_db::{defs::Definition, RootDatabase};
13 ast::{self, NameOwner},
14 match_ast, AstNode, SmolStr, TextRange,
17 use crate::FileSymbol;
19 use super::short_label::ShortLabel;
21 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
45 /// `NavigationTarget` represents and element in the editor's UI which you can
46 /// click on to navigate to a particular piece of code.
48 /// Typically, a `NavigationTarget` corresponds to some element in the source
49 /// code, like a function or a struct, but this is not strictly required.
50 #[derive(Clone, PartialEq, Eq, Hash)]
51 pub struct NavigationTarget {
53 /// Range which encompasses the whole element.
55 /// Should include body, doc comments, attributes, etc.
57 /// Clients should use this range to answer "is the cursor inside the
58 /// element?" question.
59 pub full_range: TextRange,
60 /// A "most interesting" range withing the `full_range`.
62 /// Typically, `full_range` is the whole syntax node, including doc
63 /// comments, and `focus_range` is the range of the identifier. "Most
64 /// interesting" range within the full range, typically the range of
67 /// Clients should place the cursor on this range when navigating to this target.
68 pub focus_range: Option<TextRange>,
70 pub kind: Option<SymbolKind>,
71 pub container_name: Option<SmolStr>,
72 pub description: Option<String>,
73 pub docs: Option<Documentation>,
76 impl fmt::Debug for NavigationTarget {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 let mut f = f.debug_struct("NavigationTarget");
80 ($($name:ident)*) => {$(
81 if let Some(it) = &self.$name {
82 f.field(stringify!($name), it);
86 f.field("file_id", &self.file_id).field("full_range", &self.full_range);
88 f.field("name", &self.name);
89 opt!(kind container_name description docs);
94 pub(crate) trait ToNav {
95 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget;
98 pub(crate) trait TryToNav {
99 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget>;
102 impl NavigationTarget {
103 pub fn focus_or_full_range(&self) -> TextRange {
104 self.focus_range.unwrap_or(self.full_range)
107 pub(crate) fn from_module_to_decl(db: &RootDatabase, module: hir::Module) -> NavigationTarget {
108 let name = module.name(db).map(|it| it.to_string().into()).unwrap_or_default();
109 if let Some(src) = module.declaration_source(db) {
110 let node = src.as_ref().map(|it| it.syntax());
111 let frange = node.original_file_range(db);
112 let mut res = NavigationTarget::from_syntax(
119 res.docs = module.attrs(db).docs();
120 res.description = src.value.short_label();
127 pub(crate) fn assert_match(&self, expected: &str) {
128 let actual = self.debug_render();
129 test_utils::assert_eq_text!(expected.trim(), actual.trim(),);
133 pub(crate) fn debug_render(&self) -> String {
134 let mut buf = format!(
141 if let Some(focus_range) = self.focus_range {
142 buf.push_str(&format!(" {:?}", focus_range))
144 if let Some(container_name) = &self.container_name {
145 buf.push_str(&format!(" {}", container_name))
150 /// Allows `NavigationTarget` to be created from a `NameOwner`
151 pub(crate) fn from_named(
153 node: InFile<&dyn ast::NameOwner>,
155 ) -> NavigationTarget {
157 node.value.name().map(|it| it.text().clone()).unwrap_or_else(|| SmolStr::new("_"));
159 node.value.name().map(|it| node.with_value(it.syntax()).original_file_range(db).range);
160 let frange = node.map(|it| it.syntax()).original_file_range(db);
162 NavigationTarget::from_syntax(frange.file_id, name, focus_range, frange.range, kind)
168 focus_range: Option<TextRange>,
169 full_range: TextRange,
171 ) -> NavigationTarget {
178 container_name: None,
185 impl ToNav for FileSymbol {
186 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
188 file_id: self.file_id,
189 name: self.name.clone(),
190 kind: Some(match self.kind {
191 FileSymbolKind::Function => SymbolKind::Function,
192 FileSymbolKind::Struct => SymbolKind::Struct,
193 FileSymbolKind::Enum => SymbolKind::Enum,
194 FileSymbolKind::Trait => SymbolKind::Trait,
195 FileSymbolKind::Module => SymbolKind::Module,
196 FileSymbolKind::TypeAlias => SymbolKind::TypeAlias,
197 FileSymbolKind::Const => SymbolKind::Const,
198 FileSymbolKind::Static => SymbolKind::Static,
199 FileSymbolKind::Macro => SymbolKind::Macro,
201 full_range: self.range,
202 focus_range: self.name_range,
203 container_name: self.container_name.clone(),
204 description: description_from_symbol(db, self),
210 impl TryToNav for Definition {
211 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
213 Definition::Macro(it) => {
214 // FIXME: Currently proc-macro do not have ast-node,
215 // such that it does not have source
216 // more discussion: https://github.com/rust-analyzer/rust-analyzer/issues/6913
217 if it.is_proc_macro() {
222 Definition::Field(it) => Some(it.to_nav(db)),
223 Definition::ModuleDef(it) => it.try_to_nav(db),
224 Definition::SelfType(it) => Some(it.to_nav(db)),
225 Definition::Local(it) => Some(it.to_nav(db)),
226 Definition::TypeParam(it) => Some(it.to_nav(db)),
227 Definition::LifetimeParam(it) => Some(it.to_nav(db)),
228 Definition::Label(it) => Some(it.to_nav(db)),
229 Definition::ConstParam(it) => Some(it.to_nav(db)),
234 impl TryToNav for hir::ModuleDef {
235 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
236 let res = match self {
237 hir::ModuleDef::Module(it) => it.to_nav(db),
238 hir::ModuleDef::Function(it) => it.to_nav(db),
239 hir::ModuleDef::Adt(it) => it.to_nav(db),
240 hir::ModuleDef::Variant(it) => it.to_nav(db),
241 hir::ModuleDef::Const(it) => it.to_nav(db),
242 hir::ModuleDef::Static(it) => it.to_nav(db),
243 hir::ModuleDef::Trait(it) => it.to_nav(db),
244 hir::ModuleDef::TypeAlias(it) => it.to_nav(db),
245 hir::ModuleDef::BuiltinType(_) => return None,
251 pub(crate) trait ToNavFromAst {
252 const KIND: SymbolKind;
254 impl ToNavFromAst for hir::Function {
255 const KIND: SymbolKind = SymbolKind::Function;
257 impl ToNavFromAst for hir::Const {
258 const KIND: SymbolKind = SymbolKind::Const;
260 impl ToNavFromAst for hir::Static {
261 const KIND: SymbolKind = SymbolKind::Static;
263 impl ToNavFromAst for hir::Struct {
264 const KIND: SymbolKind = SymbolKind::Struct;
266 impl ToNavFromAst for hir::Enum {
267 const KIND: SymbolKind = SymbolKind::Enum;
269 impl ToNavFromAst for hir::Variant {
270 const KIND: SymbolKind = SymbolKind::Variant;
272 impl ToNavFromAst for hir::Union {
273 const KIND: SymbolKind = SymbolKind::Union;
275 impl ToNavFromAst for hir::TypeAlias {
276 const KIND: SymbolKind = SymbolKind::TypeAlias;
278 impl ToNavFromAst for hir::Trait {
279 const KIND: SymbolKind = SymbolKind::Trait;
284 D: HasSource + ToNavFromAst + Copy + HasAttrs,
285 D::Ast: ast::NameOwner + ShortLabel,
287 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
288 let src = self.source(db);
289 let mut res = NavigationTarget::from_named(
291 src.as_ref().map(|it| it as &dyn ast::NameOwner),
294 res.docs = self.docs(db);
295 res.description = src.value.short_label();
300 impl ToNav for hir::Module {
301 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
302 let src = self.definition_source(db);
303 let name = self.name(db).map(|it| it.to_string().into()).unwrap_or_default();
304 let (syntax, focus) = match &src.value {
305 ModuleSource::SourceFile(node) => (node.syntax(), None),
306 ModuleSource::Module(node) => {
307 (node.syntax(), node.name().map(|it| it.syntax().text_range()))
310 let frange = src.with_value(syntax).original_file_range(db);
311 NavigationTarget::from_syntax(frange.file_id, name, focus, frange.range, SymbolKind::Module)
315 impl ToNav for hir::Impl {
316 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
317 let src = self.source(db);
318 let derive_attr = self.is_builtin_derive(db);
319 let frange = if let Some(item) = &derive_attr {
320 item.syntax().original_file_range(db)
322 src.as_ref().map(|it| it.syntax()).original_file_range(db)
324 let focus_range = if derive_attr.is_some() {
327 src.value.self_ty().map(|ty| src.with_value(ty.syntax()).original_file_range(db).range)
330 NavigationTarget::from_syntax(
340 impl ToNav for hir::Field {
341 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
342 let src = self.source(db);
345 FieldSource::Named(it) => {
347 NavigationTarget::from_named(db, src.with_value(it), SymbolKind::Field);
348 res.docs = self.docs(db);
349 res.description = it.short_label();
352 FieldSource::Pos(it) => {
353 let frange = src.with_value(it.syntax()).original_file_range(db);
354 NavigationTarget::from_syntax(
366 impl ToNav for hir::MacroDef {
367 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
368 let src = self.source(db);
369 log::debug!("nav target {:#?}", src.value.syntax());
370 let mut res = NavigationTarget::from_named(
372 src.as_ref().map(|it| it as &dyn ast::NameOwner),
375 res.docs = self.docs(db);
380 impl ToNav for hir::Adt {
381 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
383 hir::Adt::Struct(it) => it.to_nav(db),
384 hir::Adt::Union(it) => it.to_nav(db),
385 hir::Adt::Enum(it) => it.to_nav(db),
390 impl ToNav for hir::AssocItem {
391 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
393 AssocItem::Function(it) => it.to_nav(db),
394 AssocItem::Const(it) => it.to_nav(db),
395 AssocItem::TypeAlias(it) => it.to_nav(db),
400 impl ToNav for hir::Local {
401 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
402 let src = self.source(db);
403 let node = match &src.value {
404 Either::Left(bind_pat) => {
405 bind_pat.name().map_or_else(|| bind_pat.syntax().clone(), |it| it.syntax().clone())
407 Either::Right(it) => it.syntax().clone(),
409 let full_range = src.with_value(&node).original_file_range(db);
410 let name = match self.name(db) {
411 Some(it) => it.to_string().into(),
414 let kind = if self.is_param(db) { SymbolKind::ValueParam } else { SymbolKind::Local };
416 file_id: full_range.file_id,
419 full_range: full_range.range,
421 container_name: None,
428 impl ToNav for hir::Label {
429 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
430 let src = self.source(db);
431 let node = src.value.syntax();
432 let FileRange { file_id, range } = src.with_value(node).original_file_range(db);
434 src.value.lifetime().and_then(|lt| lt.lifetime_ident_token()).map(|lt| lt.text_range());
435 let name = self.name(db).to_string().into();
439 kind: Some(SymbolKind::Label),
442 container_name: None,
449 impl ToNav for hir::TypeParam {
450 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
451 let src = self.source(db);
452 let full_range = match &src.value {
453 Either::Left(it) => it.syntax().text_range(),
454 Either::Right(it) => it.syntax().text_range(),
456 let focus_range = match &src.value {
457 Either::Left(_) => None,
458 Either::Right(it) => it.name().map(|it| it.syntax().text_range()),
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 ToNav for hir::LifetimeParam {
474 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
475 let src = self.source(db);
476 let full_range = src.value.syntax().text_range();
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 ToNav for hir::ConstParam {
491 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
492 let src = self.source(db);
493 let full_range = src.value.syntax().text_range();
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 parse = db.parse(symbol.file_id);
512 let node = symbol.ptr.to_node(parse.tree().syntax());
516 ast::Fn(it) => it.short_label(),
517 ast::Struct(it) => it.short_label(),
518 ast::Enum(it) => it.short_label(),
519 ast::Trait(it) => it.short_label(),
520 ast::Module(it) => it.short_label(),
521 ast::TypeAlias(it) => it.short_label(),
522 ast::Const(it) => it.short_label(),
523 ast::Static(it) => it.short_label(),
524 ast::RecordField(it) => it.short_label(),
525 ast::Variant(it) => it.short_label(),
533 use expect_test::expect;
535 use crate::{fixture, Query};
538 fn test_nav_for_symbol() {
539 let (analysis, _) = fixture::file(
542 fn foo() { enum FooInner { } }
546 let navs = analysis.symbol_search(Query::new("FooInner".to_string())).unwrap();
557 description: "enum FooInner",
567 container_name: "foo",
568 description: "enum FooInner",
572 .assert_debug_eq(&navs);
576 fn test_world_symbols_are_case_sensitive() {
577 let (analysis, _) = fixture::file(
584 let navs = analysis.symbol_search(Query::new("foo".to_string())).unwrap();
585 assert_eq!(navs.len(), 2)