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)]
44 /// `NavigationTarget` represents and element in the editor's UI which you can
45 /// click on to navigate to a particular piece of code.
47 /// Typically, a `NavigationTarget` corresponds to some element in the source
48 /// code, like a function or a struct, but this is not strictly required.
49 #[derive(Clone, PartialEq, Eq, Hash)]
50 pub struct NavigationTarget {
52 /// Range which encompasses the whole element.
54 /// Should include body, doc comments, attributes, etc.
56 /// Clients should use this range to answer "is the cursor inside the
57 /// element?" question.
58 pub full_range: TextRange,
59 /// A "most interesting" range withing the `full_range`.
61 /// Typically, `full_range` is the whole syntax node, including doc
62 /// comments, and `focus_range` is the range of the identifier. "Most
63 /// interesting" range within the full range, typically the range of
66 /// Clients should place the cursor on this range when navigating to this target.
67 pub focus_range: Option<TextRange>,
69 pub kind: Option<SymbolKind>,
70 pub container_name: Option<SmolStr>,
71 pub description: Option<String>,
72 pub docs: Option<Documentation>,
75 impl fmt::Debug for NavigationTarget {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 let mut f = f.debug_struct("NavigationTarget");
79 ($($name:ident)*) => {$(
80 if let Some(it) = &self.$name {
81 f.field(stringify!($name), it);
85 f.field("file_id", &self.file_id).field("full_range", &self.full_range);
87 f.field("name", &self.name);
88 opt!(kind container_name description docs);
93 pub(crate) trait ToNav {
94 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget;
97 pub(crate) trait TryToNav {
98 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget>;
101 impl NavigationTarget {
102 pub fn focus_or_full_range(&self) -> TextRange {
103 self.focus_range.unwrap_or(self.full_range)
106 pub(crate) fn from_module_to_decl(db: &RootDatabase, module: hir::Module) -> NavigationTarget {
107 let name = module.name(db).map(|it| it.to_string().into()).unwrap_or_default();
108 if let Some(src) = module.declaration_source(db) {
109 let node = src.as_ref().map(|it| it.syntax());
110 let frange = node.original_file_range(db);
111 let mut res = NavigationTarget::from_syntax(
118 res.docs = module.attrs(db).docs();
119 res.description = src.value.short_label();
126 pub(crate) fn assert_match(&self, expected: &str) {
127 let actual = self.debug_render();
128 test_utils::assert_eq_text!(expected.trim(), actual.trim(),);
132 pub(crate) fn debug_render(&self) -> String {
133 let mut buf = format!(
140 if let Some(focus_range) = self.focus_range {
141 buf.push_str(&format!(" {:?}", focus_range))
143 if let Some(container_name) = &self.container_name {
144 buf.push_str(&format!(" {}", container_name))
149 /// Allows `NavigationTarget` to be created from a `NameOwner`
150 pub(crate) fn from_named(
152 node: InFile<&dyn ast::NameOwner>,
154 ) -> NavigationTarget {
156 node.value.name().map(|it| it.text().clone()).unwrap_or_else(|| SmolStr::new("_"));
158 node.value.name().map(|it| node.with_value(it.syntax()).original_file_range(db).range);
159 let frange = node.map(|it| it.syntax()).original_file_range(db);
161 NavigationTarget::from_syntax(frange.file_id, name, focus_range, frange.range, kind)
167 focus_range: Option<TextRange>,
168 full_range: TextRange,
170 ) -> NavigationTarget {
177 container_name: None,
184 impl ToNav for FileSymbol {
185 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
187 file_id: self.file_id,
188 name: self.name.clone(),
189 kind: Some(match self.kind {
190 FileSymbolKind::Function => SymbolKind::Function,
191 FileSymbolKind::Struct => SymbolKind::Struct,
192 FileSymbolKind::Enum => SymbolKind::Enum,
193 FileSymbolKind::Trait => SymbolKind::Trait,
194 FileSymbolKind::Module => SymbolKind::Module,
195 FileSymbolKind::TypeAlias => SymbolKind::TypeAlias,
196 FileSymbolKind::Const => SymbolKind::Const,
197 FileSymbolKind::Static => SymbolKind::Static,
198 FileSymbolKind::Macro => SymbolKind::Macro,
200 full_range: self.range,
201 focus_range: self.name_range,
202 container_name: self.container_name.clone(),
203 description: description_from_symbol(db, self),
209 impl TryToNav for Definition {
210 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
212 Definition::Macro(it) => {
213 // FIXME: Currently proc-macro do not have ast-node,
214 // such that it does not have source
215 // more discussion: https://github.com/rust-analyzer/rust-analyzer/issues/6913
216 if it.is_proc_macro() {
221 Definition::Field(it) => Some(it.to_nav(db)),
222 Definition::ModuleDef(it) => it.try_to_nav(db),
223 Definition::SelfType(it) => Some(it.to_nav(db)),
224 Definition::Local(it) => Some(it.to_nav(db)),
225 Definition::TypeParam(it) => Some(it.to_nav(db)),
226 Definition::LifetimeParam(it) => Some(it.to_nav(db)),
227 Definition::Label(it) => Some(it.to_nav(db)),
232 impl TryToNav for hir::ModuleDef {
233 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
234 let res = match self {
235 hir::ModuleDef::Module(it) => it.to_nav(db),
236 hir::ModuleDef::Function(it) => it.to_nav(db),
237 hir::ModuleDef::Adt(it) => it.to_nav(db),
238 hir::ModuleDef::Variant(it) => it.to_nav(db),
239 hir::ModuleDef::Const(it) => it.to_nav(db),
240 hir::ModuleDef::Static(it) => it.to_nav(db),
241 hir::ModuleDef::Trait(it) => it.to_nav(db),
242 hir::ModuleDef::TypeAlias(it) => it.to_nav(db),
243 hir::ModuleDef::BuiltinType(_) => return None,
249 pub(crate) trait ToNavFromAst {
250 const KIND: SymbolKind;
252 impl ToNavFromAst for hir::Function {
253 const KIND: SymbolKind = SymbolKind::Function;
255 impl ToNavFromAst for hir::Const {
256 const KIND: SymbolKind = SymbolKind::Const;
258 impl ToNavFromAst for hir::Static {
259 const KIND: SymbolKind = SymbolKind::Static;
261 impl ToNavFromAst for hir::Struct {
262 const KIND: SymbolKind = SymbolKind::Struct;
264 impl ToNavFromAst for hir::Enum {
265 const KIND: SymbolKind = SymbolKind::Enum;
267 impl ToNavFromAst for hir::Variant {
268 const KIND: SymbolKind = SymbolKind::Variant;
270 impl ToNavFromAst for hir::Union {
271 const KIND: SymbolKind = SymbolKind::Union;
273 impl ToNavFromAst for hir::TypeAlias {
274 const KIND: SymbolKind = SymbolKind::TypeAlias;
276 impl ToNavFromAst for hir::Trait {
277 const KIND: SymbolKind = SymbolKind::Trait;
282 D: HasSource + ToNavFromAst + Copy + HasAttrs,
283 D::Ast: ast::NameOwner + ShortLabel,
285 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
286 let src = self.source(db);
287 let mut res = NavigationTarget::from_named(
289 src.as_ref().map(|it| it as &dyn ast::NameOwner),
292 res.docs = self.docs(db);
293 res.description = src.value.short_label();
298 impl ToNav for hir::Module {
299 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
300 let src = self.definition_source(db);
301 let name = self.name(db).map(|it| it.to_string().into()).unwrap_or_default();
302 let (syntax, focus) = match &src.value {
303 ModuleSource::SourceFile(node) => (node.syntax(), None),
304 ModuleSource::Module(node) => {
305 (node.syntax(), node.name().map(|it| it.syntax().text_range()))
308 let frange = src.with_value(syntax).original_file_range(db);
309 NavigationTarget::from_syntax(frange.file_id, name, focus, frange.range, SymbolKind::Module)
313 impl ToNav for hir::Impl {
314 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
315 let src = self.source(db);
316 let derive_attr = self.is_builtin_derive(db);
317 let frange = if let Some(item) = &derive_attr {
318 item.syntax().original_file_range(db)
320 src.as_ref().map(|it| it.syntax()).original_file_range(db)
322 let focus_range = if derive_attr.is_some() {
325 src.value.self_ty().map(|ty| src.with_value(ty.syntax()).original_file_range(db).range)
328 NavigationTarget::from_syntax(
338 impl ToNav for hir::Field {
339 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
340 let src = self.source(db);
343 FieldSource::Named(it) => {
345 NavigationTarget::from_named(db, src.with_value(it), SymbolKind::Field);
346 res.docs = self.docs(db);
347 res.description = it.short_label();
350 FieldSource::Pos(it) => {
351 let frange = src.with_value(it.syntax()).original_file_range(db);
352 NavigationTarget::from_syntax(
364 impl ToNav for hir::MacroDef {
365 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
366 let src = self.source(db);
367 log::debug!("nav target {:#?}", src.value.syntax());
368 let mut res = NavigationTarget::from_named(
370 src.as_ref().map(|it| it as &dyn ast::NameOwner),
373 res.docs = self.docs(db);
378 impl ToNav for hir::Adt {
379 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
381 hir::Adt::Struct(it) => it.to_nav(db),
382 hir::Adt::Union(it) => it.to_nav(db),
383 hir::Adt::Enum(it) => it.to_nav(db),
388 impl ToNav for hir::AssocItem {
389 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
391 AssocItem::Function(it) => it.to_nav(db),
392 AssocItem::Const(it) => it.to_nav(db),
393 AssocItem::TypeAlias(it) => it.to_nav(db),
398 impl ToNav for hir::Local {
399 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
400 let src = self.source(db);
401 let node = match &src.value {
402 Either::Left(bind_pat) => {
403 bind_pat.name().map_or_else(|| bind_pat.syntax().clone(), |it| it.syntax().clone())
405 Either::Right(it) => it.syntax().clone(),
407 let full_range = src.with_value(&node).original_file_range(db);
408 let name = match self.name(db) {
409 Some(it) => it.to_string().into(),
412 let kind = if self.is_param(db) { SymbolKind::ValueParam } else { SymbolKind::Local };
414 file_id: full_range.file_id,
417 full_range: full_range.range,
419 container_name: None,
426 impl ToNav for hir::Label {
427 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
428 let src = self.source(db);
429 let node = src.value.syntax();
430 let FileRange { file_id, range } = src.with_value(node).original_file_range(db);
432 src.value.lifetime().and_then(|lt| lt.lifetime_ident_token()).map(|lt| lt.text_range());
433 let name = self.name(db).to_string().into();
437 kind: Some(SymbolKind::Label),
440 container_name: None,
447 impl ToNav for hir::TypeParam {
448 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
449 let src = self.source(db);
450 let full_range = match &src.value {
451 Either::Left(it) => it.syntax().text_range(),
452 Either::Right(it) => it.syntax().text_range(),
454 let focus_range = match &src.value {
455 Either::Left(_) => None,
456 Either::Right(it) => it.name().map(|it| it.syntax().text_range()),
459 file_id: src.file_id.original_file(db),
460 name: self.name(db).to_string().into(),
461 kind: Some(SymbolKind::TypeParam),
464 container_name: None,
471 impl ToNav for hir::LifetimeParam {
472 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
473 let src = self.source(db);
474 let full_range = src.value.syntax().text_range();
476 file_id: src.file_id.original_file(db),
477 name: self.name(db).to_string().into(),
478 kind: Some(SymbolKind::LifetimeParam),
480 focus_range: Some(full_range),
481 container_name: None,
488 /// Get a description of a symbol.
490 /// e.g. `struct Name`, `enum Name`, `fn Name`
491 pub(crate) fn description_from_symbol(db: &RootDatabase, symbol: &FileSymbol) -> Option<String> {
492 let parse = db.parse(symbol.file_id);
493 let node = symbol.ptr.to_node(parse.tree().syntax());
497 ast::Fn(it) => it.short_label(),
498 ast::Struct(it) => it.short_label(),
499 ast::Enum(it) => it.short_label(),
500 ast::Trait(it) => it.short_label(),
501 ast::Module(it) => it.short_label(),
502 ast::TypeAlias(it) => it.short_label(),
503 ast::Const(it) => it.short_label(),
504 ast::Static(it) => it.short_label(),
505 ast::RecordField(it) => it.short_label(),
506 ast::Variant(it) => it.short_label(),
514 use expect_test::expect;
516 use crate::{fixture, Query};
519 fn test_nav_for_symbol() {
520 let (analysis, _) = fixture::file(
523 fn foo() { enum FooInner { } }
527 let navs = analysis.symbol_search(Query::new("FooInner".to_string())).unwrap();
538 description: "enum FooInner",
548 container_name: "foo",
549 description: "enum FooInner",
553 .assert_debug_eq(&navs);
557 fn test_world_symbols_are_case_sensitive() {
558 let (analysis, _) = fixture::file(
565 let navs = analysis.symbol_search(Query::new("foo".to_string())).unwrap();
566 assert_eq!(navs.len(), 2)