1 //! FIXME: write short doc here
6 use hir::{AssocItem, Documentation, FieldSource, HasAttrs, HasSource, InFile, ModuleSource};
8 base_db::{FileId, 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)]
43 /// `NavigationTarget` represents and element in the editor's UI which you can
44 /// click on to navigate to a particular piece of code.
46 /// Typically, a `NavigationTarget` corresponds to some element in the source
47 /// code, like a function or a struct, but this is not strictly required.
48 #[derive(Clone, PartialEq, Eq, Hash)]
49 pub struct NavigationTarget {
51 /// Range which encompasses the whole element.
53 /// Should include body, doc comments, attributes, etc.
55 /// Clients should use this range to answer "is the cursor inside the
56 /// element?" question.
57 pub full_range: TextRange,
58 /// A "most interesting" range withing the `full_range`.
60 /// Typically, `full_range` is the whole syntax node, including doc
61 /// comments, and `focus_range` is the range of the identifier. "Most
62 /// interesting" range within the full range, typically the range of
65 /// Clients should place the cursor on this range when navigating to this target.
66 pub focus_range: Option<TextRange>,
68 pub kind: Option<SymbolKind>,
69 pub container_name: Option<SmolStr>,
70 pub description: Option<String>,
71 pub docs: Option<Documentation>,
74 impl fmt::Debug for NavigationTarget {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 let mut f = f.debug_struct("NavigationTarget");
78 ($($name:ident)*) => {$(
79 if let Some(it) = &self.$name {
80 f.field(stringify!($name), it);
84 f.field("file_id", &self.file_id).field("full_range", &self.full_range);
86 f.field("name", &self.name);
87 opt!(kind container_name description docs);
92 pub(crate) trait ToNav {
93 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget;
96 pub(crate) trait TryToNav {
97 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget>;
100 impl NavigationTarget {
101 pub fn focus_or_full_range(&self) -> TextRange {
102 self.focus_range.unwrap_or(self.full_range)
105 pub(crate) fn from_module_to_decl(db: &RootDatabase, module: hir::Module) -> NavigationTarget {
106 let name = module.name(db).map(|it| it.to_string().into()).unwrap_or_default();
107 if let Some(src) = module.declaration_source(db) {
108 let node = src.as_ref().map(|it| it.syntax());
109 let frange = node.original_file_range(db);
110 let mut res = NavigationTarget::from_syntax(
117 res.docs = module.attrs(db).docs();
118 res.description = src.value.short_label();
125 pub(crate) fn assert_match(&self, expected: &str) {
126 let actual = self.debug_render();
127 test_utils::assert_eq_text!(expected.trim(), actual.trim(),);
131 pub(crate) fn debug_render(&self) -> String {
132 let mut buf = format!(
139 if let Some(focus_range) = self.focus_range {
140 buf.push_str(&format!(" {:?}", focus_range))
142 if let Some(container_name) = &self.container_name {
143 buf.push_str(&format!(" {}", container_name))
148 /// Allows `NavigationTarget` to be created from a `NameOwner`
149 pub(crate) fn from_named(
151 node: InFile<&dyn ast::NameOwner>,
153 ) -> NavigationTarget {
155 node.value.name().map(|it| it.text().clone()).unwrap_or_else(|| SmolStr::new("_"));
157 node.value.name().map(|it| node.with_value(it.syntax()).original_file_range(db).range);
158 let frange = node.map(|it| it.syntax()).original_file_range(db);
160 NavigationTarget::from_syntax(frange.file_id, name, focus_range, frange.range, kind)
166 focus_range: Option<TextRange>,
167 full_range: TextRange,
169 ) -> NavigationTarget {
176 container_name: None,
183 impl ToNav for FileSymbol {
184 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
186 file_id: self.file_id,
187 name: self.name.clone(),
188 kind: Some(match self.kind {
189 FileSymbolKind::Function => SymbolKind::Function,
190 FileSymbolKind::Struct => SymbolKind::Struct,
191 FileSymbolKind::Enum => SymbolKind::Enum,
192 FileSymbolKind::Trait => SymbolKind::Trait,
193 FileSymbolKind::Module => SymbolKind::Module,
194 FileSymbolKind::TypeAlias => SymbolKind::TypeAlias,
195 FileSymbolKind::Const => SymbolKind::Const,
196 FileSymbolKind::Static => SymbolKind::Static,
197 FileSymbolKind::Macro => SymbolKind::Macro,
199 full_range: self.range,
200 focus_range: self.name_range,
201 container_name: self.container_name.clone(),
202 description: description_from_symbol(db, self),
208 impl TryToNav for Definition {
209 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
211 Definition::Macro(it) => {
212 // FIXME: Currently proc-macro do not have ast-node,
213 // such that it does not have source
214 // more discussion: https://github.com/rust-analyzer/rust-analyzer/issues/6913
215 if it.is_proc_macro() {
220 Definition::Field(it) => Some(it.to_nav(db)),
221 Definition::ModuleDef(it) => it.try_to_nav(db),
222 Definition::SelfType(it) => Some(it.to_nav(db)),
223 Definition::Local(it) => Some(it.to_nav(db)),
224 Definition::TypeParam(it) => Some(it.to_nav(db)),
225 Definition::LifetimeParam(it) => Some(it.to_nav(db)),
230 impl TryToNav for hir::ModuleDef {
231 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
232 let res = match self {
233 hir::ModuleDef::Module(it) => it.to_nav(db),
234 hir::ModuleDef::Function(it) => it.to_nav(db),
235 hir::ModuleDef::Adt(it) => it.to_nav(db),
236 hir::ModuleDef::EnumVariant(it) => it.to_nav(db),
237 hir::ModuleDef::Const(it) => it.to_nav(db),
238 hir::ModuleDef::Static(it) => it.to_nav(db),
239 hir::ModuleDef::Trait(it) => it.to_nav(db),
240 hir::ModuleDef::TypeAlias(it) => it.to_nav(db),
241 hir::ModuleDef::BuiltinType(_) => return None,
247 pub(crate) trait ToNavFromAst {
248 const KIND: SymbolKind;
250 impl ToNavFromAst for hir::Function {
251 const KIND: SymbolKind = SymbolKind::Function;
253 impl ToNavFromAst for hir::Const {
254 const KIND: SymbolKind = SymbolKind::Const;
256 impl ToNavFromAst for hir::Static {
257 const KIND: SymbolKind = SymbolKind::Static;
259 impl ToNavFromAst for hir::Struct {
260 const KIND: SymbolKind = SymbolKind::Struct;
262 impl ToNavFromAst for hir::Enum {
263 const KIND: SymbolKind = SymbolKind::Enum;
265 impl ToNavFromAst for hir::EnumVariant {
266 const KIND: SymbolKind = SymbolKind::Variant;
268 impl ToNavFromAst for hir::Union {
269 const KIND: SymbolKind = SymbolKind::Union;
271 impl ToNavFromAst for hir::TypeAlias {
272 const KIND: SymbolKind = SymbolKind::TypeAlias;
274 impl ToNavFromAst for hir::Trait {
275 const KIND: SymbolKind = SymbolKind::Trait;
280 D: HasSource + ToNavFromAst + Copy + HasAttrs,
281 D::Ast: ast::NameOwner + ShortLabel,
283 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
284 let src = self.source(db);
285 let mut res = NavigationTarget::from_named(
287 src.as_ref().map(|it| it as &dyn ast::NameOwner),
290 res.docs = self.docs(db);
291 res.description = src.value.short_label();
296 impl ToNav for hir::Module {
297 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
298 let src = self.definition_source(db);
299 let name = self.name(db).map(|it| it.to_string().into()).unwrap_or_default();
300 let (syntax, focus) = match &src.value {
301 ModuleSource::SourceFile(node) => (node.syntax(), None),
302 ModuleSource::Module(node) => {
303 (node.syntax(), node.name().map(|it| it.syntax().text_range()))
306 let frange = src.with_value(syntax).original_file_range(db);
307 NavigationTarget::from_syntax(frange.file_id, name, focus, frange.range, SymbolKind::Module)
311 impl ToNav for hir::Impl {
312 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
313 let src = self.source(db);
314 let derive_attr = self.is_builtin_derive(db);
315 let frange = if let Some(item) = &derive_attr {
316 item.syntax().original_file_range(db)
318 src.as_ref().map(|it| it.syntax()).original_file_range(db)
320 let focus_range = if derive_attr.is_some() {
323 src.value.self_ty().map(|ty| src.with_value(ty.syntax()).original_file_range(db).range)
326 NavigationTarget::from_syntax(
336 impl ToNav for hir::Field {
337 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
338 let src = self.source(db);
341 FieldSource::Named(it) => {
343 NavigationTarget::from_named(db, src.with_value(it), SymbolKind::Field);
344 res.docs = self.docs(db);
345 res.description = it.short_label();
348 FieldSource::Pos(it) => {
349 let frange = src.with_value(it.syntax()).original_file_range(db);
350 NavigationTarget::from_syntax(
362 impl ToNav for hir::MacroDef {
363 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
364 let src = self.source(db);
365 log::debug!("nav target {:#?}", src.value.syntax());
366 let mut res = NavigationTarget::from_named(
368 src.as_ref().map(|it| it as &dyn ast::NameOwner),
371 res.docs = self.docs(db);
376 impl ToNav for hir::Adt {
377 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
379 hir::Adt::Struct(it) => it.to_nav(db),
380 hir::Adt::Union(it) => it.to_nav(db),
381 hir::Adt::Enum(it) => it.to_nav(db),
386 impl ToNav for hir::AssocItem {
387 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
389 AssocItem::Function(it) => it.to_nav(db),
390 AssocItem::Const(it) => it.to_nav(db),
391 AssocItem::TypeAlias(it) => it.to_nav(db),
396 impl ToNav for hir::Local {
397 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
398 let src = self.source(db);
399 let node = match &src.value {
400 Either::Left(bind_pat) => {
401 bind_pat.name().map_or_else(|| bind_pat.syntax().clone(), |it| it.syntax().clone())
403 Either::Right(it) => it.syntax().clone(),
405 let full_range = src.with_value(&node).original_file_range(db);
406 let name = match self.name(db) {
407 Some(it) => it.to_string().into(),
410 let kind = if self.is_param(db) { SymbolKind::ValueParam } else { SymbolKind::Local };
412 file_id: full_range.file_id,
415 full_range: full_range.range,
417 container_name: None,
424 impl ToNav for hir::TypeParam {
425 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
426 let src = self.source(db);
427 let full_range = match &src.value {
428 Either::Left(it) => it.syntax().text_range(),
429 Either::Right(it) => it.syntax().text_range(),
431 let focus_range = match &src.value {
432 Either::Left(_) => None,
433 Either::Right(it) => it.name().map(|it| it.syntax().text_range()),
436 file_id: src.file_id.original_file(db),
437 name: self.name(db).to_string().into(),
438 kind: Some(SymbolKind::TypeParam),
441 container_name: None,
448 impl ToNav for hir::LifetimeParam {
449 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
450 let src = self.source(db);
451 let full_range = src.value.syntax().text_range();
453 file_id: src.file_id.original_file(db),
454 name: self.name(db).to_string().into(),
455 kind: Some(SymbolKind::LifetimeParam),
457 focus_range: Some(full_range),
458 container_name: None,
465 /// Get a description of a symbol.
467 /// e.g. `struct Name`, `enum Name`, `fn Name`
468 pub(crate) fn description_from_symbol(db: &RootDatabase, symbol: &FileSymbol) -> Option<String> {
469 let parse = db.parse(symbol.file_id);
470 let node = symbol.ptr.to_node(parse.tree().syntax());
474 ast::Fn(it) => it.short_label(),
475 ast::Struct(it) => it.short_label(),
476 ast::Enum(it) => it.short_label(),
477 ast::Trait(it) => it.short_label(),
478 ast::Module(it) => it.short_label(),
479 ast::TypeAlias(it) => it.short_label(),
480 ast::Const(it) => it.short_label(),
481 ast::Static(it) => it.short_label(),
482 ast::RecordField(it) => it.short_label(),
483 ast::Variant(it) => it.short_label(),
491 use expect_test::expect;
493 use crate::{fixture, Query};
496 fn test_nav_for_symbol() {
497 let (analysis, _) = fixture::file(
500 fn foo() { enum FooInner { } }
504 let navs = analysis.symbol_search(Query::new("FooInner".to_string())).unwrap();
515 description: "enum FooInner",
525 container_name: "foo",
526 description: "enum FooInner",
530 .assert_debug_eq(&navs);
534 fn test_world_symbols_are_case_sensitive() {
535 let (analysis, _) = fixture::file(
542 let navs = analysis.symbol_search(Query::new("foo".to_string())).unwrap();
543 assert_eq!(navs.len(), 2)