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) => it.try_to_nav(db),
214 Definition::Field(it) => it.try_to_nav(db),
215 Definition::ModuleDef(it) => it.try_to_nav(db),
216 Definition::SelfType(it) => it.try_to_nav(db),
217 Definition::Local(it) => Some(it.to_nav(db)),
218 Definition::TypeParam(it) => it.try_to_nav(db),
219 Definition::LifetimeParam(it) => it.try_to_nav(db),
220 Definition::Label(it) => Some(it.to_nav(db)),
221 Definition::ConstParam(it) => it.try_to_nav(db),
226 impl TryToNav for hir::ModuleDef {
227 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
229 hir::ModuleDef::Module(it) => Some(it.to_nav(db)),
230 hir::ModuleDef::Function(it) => it.try_to_nav(db),
231 hir::ModuleDef::Adt(it) => it.try_to_nav(db),
232 hir::ModuleDef::Variant(it) => it.try_to_nav(db),
233 hir::ModuleDef::Const(it) => it.try_to_nav(db),
234 hir::ModuleDef::Static(it) => it.try_to_nav(db),
235 hir::ModuleDef::Trait(it) => it.try_to_nav(db),
236 hir::ModuleDef::TypeAlias(it) => it.try_to_nav(db),
237 hir::ModuleDef::BuiltinType(_) => None,
242 pub(crate) trait ToNavFromAst {
243 const KIND: SymbolKind;
245 impl ToNavFromAst for hir::Function {
246 const KIND: SymbolKind = SymbolKind::Function;
248 impl ToNavFromAst for hir::Const {
249 const KIND: SymbolKind = SymbolKind::Const;
251 impl ToNavFromAst for hir::Static {
252 const KIND: SymbolKind = SymbolKind::Static;
254 impl ToNavFromAst for hir::Struct {
255 const KIND: SymbolKind = SymbolKind::Struct;
257 impl ToNavFromAst for hir::Enum {
258 const KIND: SymbolKind = SymbolKind::Enum;
260 impl ToNavFromAst for hir::Variant {
261 const KIND: SymbolKind = SymbolKind::Variant;
263 impl ToNavFromAst for hir::Union {
264 const KIND: SymbolKind = SymbolKind::Union;
266 impl ToNavFromAst for hir::TypeAlias {
267 const KIND: SymbolKind = SymbolKind::TypeAlias;
269 impl ToNavFromAst for hir::Trait {
270 const KIND: SymbolKind = SymbolKind::Trait;
273 impl<D> TryToNav for D
275 D: HasSource + ToNavFromAst + Copy + HasAttrs,
276 D::Ast: ast::NameOwner + ShortLabel,
278 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
279 let src = self.source(db)?;
280 let mut res = NavigationTarget::from_named(
282 src.as_ref().map(|it| it as &dyn ast::NameOwner),
285 res.docs = self.docs(db);
286 res.description = src.value.short_label();
291 impl ToNav for hir::Module {
292 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
293 let src = self.definition_source(db);
294 let name = self.name(db).map(|it| it.to_string().into()).unwrap_or_default();
295 let (syntax, focus) = match &src.value {
296 ModuleSource::SourceFile(node) => (node.syntax(), None),
297 ModuleSource::Module(node) => {
298 (node.syntax(), node.name().map(|it| it.syntax().text_range()))
301 let frange = src.with_value(syntax).original_file_range(db);
302 NavigationTarget::from_syntax(frange.file_id, name, focus, frange.range, SymbolKind::Module)
306 impl TryToNav for hir::Impl {
307 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
308 let src = self.source(db)?;
309 let derive_attr = self.is_builtin_derive(db);
310 let frange = if let Some(item) = &derive_attr {
311 item.syntax().original_file_range(db)
313 src.as_ref().map(|it| it.syntax()).original_file_range(db)
315 let focus_range = if derive_attr.is_some() {
318 src.value.self_ty().map(|ty| src.with_value(ty.syntax()).original_file_range(db).range)
321 Some(NavigationTarget::from_syntax(
331 impl TryToNav for hir::Field {
332 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
333 let src = self.source(db)?;
335 let field_source = match &src.value {
336 FieldSource::Named(it) => {
338 NavigationTarget::from_named(db, src.with_value(it), SymbolKind::Field);
339 res.docs = self.docs(db);
340 res.description = it.short_label();
343 FieldSource::Pos(it) => {
344 let frange = src.with_value(it.syntax()).original_file_range(db);
345 NavigationTarget::from_syntax(
358 impl TryToNav for hir::MacroDef {
359 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
360 let src = self.source(db)?;
361 log::debug!("nav target {:#?}", src.value.syntax());
362 let mut res = NavigationTarget::from_named(
364 src.as_ref().map(|it| it as &dyn ast::NameOwner),
367 res.docs = self.docs(db);
372 impl TryToNav for hir::Adt {
373 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
375 hir::Adt::Struct(it) => it.try_to_nav(db),
376 hir::Adt::Union(it) => it.try_to_nav(db),
377 hir::Adt::Enum(it) => it.try_to_nav(db),
382 impl TryToNav for hir::AssocItem {
383 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
385 AssocItem::Function(it) => it.try_to_nav(db),
386 AssocItem::Const(it) => it.try_to_nav(db),
387 AssocItem::TypeAlias(it) => it.try_to_nav(db),
392 impl ToNav for hir::Local {
393 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
394 let src = self.source(db);
395 let node = match &src.value {
396 Either::Left(bind_pat) => {
397 bind_pat.name().map_or_else(|| bind_pat.syntax().clone(), |it| it.syntax().clone())
399 Either::Right(it) => it.syntax().clone(),
401 let full_range = src.with_value(&node).original_file_range(db);
402 let name = match self.name(db) {
403 Some(it) => it.to_string().into(),
406 let kind = if self.is_param(db) { SymbolKind::ValueParam } else { SymbolKind::Local };
408 file_id: full_range.file_id,
411 full_range: full_range.range,
413 container_name: None,
420 impl ToNav for hir::Label {
421 fn to_nav(&self, db: &RootDatabase) -> NavigationTarget {
422 let src = self.source(db);
423 let node = src.value.syntax();
424 let FileRange { file_id, range } = src.with_value(node).original_file_range(db);
426 src.value.lifetime().and_then(|lt| lt.lifetime_ident_token()).map(|lt| lt.text_range());
427 let name = self.name(db).to_string().into();
431 kind: Some(SymbolKind::Label),
434 container_name: None,
441 impl TryToNav for hir::TypeParam {
442 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
443 let src = self.source(db)?;
444 let full_range = match &src.value {
445 Either::Left(it) => it.syntax().text_range(),
446 Either::Right(it) => it.syntax().text_range(),
448 let focus_range = match &src.value {
449 Either::Left(_) => None,
450 Either::Right(it) => it.name().map(|it| it.syntax().text_range()),
452 Some(NavigationTarget {
453 file_id: src.file_id.original_file(db),
454 name: self.name(db).to_string().into(),
455 kind: Some(SymbolKind::TypeParam),
458 container_name: None,
465 impl TryToNav for hir::LifetimeParam {
466 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
467 let src = self.source(db)?;
468 let full_range = src.value.syntax().text_range();
469 Some(NavigationTarget {
470 file_id: src.file_id.original_file(db),
471 name: self.name(db).to_string().into(),
472 kind: Some(SymbolKind::LifetimeParam),
474 focus_range: Some(full_range),
475 container_name: None,
482 impl TryToNav for hir::ConstParam {
483 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
484 let src = self.source(db)?;
485 let full_range = src.value.syntax().text_range();
486 Some(NavigationTarget {
487 file_id: src.file_id.original_file(db),
488 name: self.name(db).to_string().into(),
489 kind: Some(SymbolKind::ConstParam),
491 focus_range: src.value.name().map(|n| n.syntax().text_range()),
492 container_name: None,
499 /// Get a description of a symbol.
501 /// e.g. `struct Name`, `enum Name`, `fn Name`
502 pub(crate) fn description_from_symbol(db: &RootDatabase, symbol: &FileSymbol) -> Option<String> {
503 let parse = db.parse(symbol.file_id);
504 let node = symbol.ptr.to_node(parse.tree().syntax());
508 ast::Fn(it) => it.short_label(),
509 ast::Struct(it) => it.short_label(),
510 ast::Enum(it) => it.short_label(),
511 ast::Trait(it) => it.short_label(),
512 ast::Module(it) => it.short_label(),
513 ast::TypeAlias(it) => it.short_label(),
514 ast::Const(it) => it.short_label(),
515 ast::Static(it) => it.short_label(),
516 ast::RecordField(it) => it.short_label(),
517 ast::Variant(it) => it.short_label(),
525 use expect_test::expect;
527 use crate::{fixture, Query};
530 fn test_nav_for_symbol() {
531 let (analysis, _) = fixture::file(
534 fn foo() { enum FooInner { } }
538 let navs = analysis.symbol_search(Query::new("FooInner".to_string())).unwrap();
549 description: "enum FooInner",
559 container_name: "foo",
560 description: "enum FooInner",
564 .assert_debug_eq(&navs);
568 fn test_world_symbols_are_case_sensitive() {
569 let (analysis, _) = fixture::file(
576 let navs = analysis.symbol_search(Query::new("foo".to_string())).unwrap();
577 assert_eq!(navs.len(), 2)