1 //! This module implements a reference search.
2 //! First, the element at the cursor position must be either an `ast::Name`
3 //! or `ast::NameRef`. If it's an `ast::NameRef`, at the classification step we
4 //! try to resolve the direct tree parent of this element, otherwise we
5 //! already have a definition and just need to get its HIR together with
6 //! some information that is needed for further steps of searching.
7 //! After that, we collect files that might contain references and look
8 //! for text occurrences of the identifier. If there's an `ast::NameRef`
9 //! at the index that the match starts at and its tree parent is
10 //! resolved to the search element definition, we get a reference.
12 use hir::{PathResolution, Semantics};
15 defs::{Definition, NameClass, NameRefClass},
16 search::{ReferenceCategory, SearchScope, UsageSearchResult},
17 FxHashMap, RootDatabase,
20 algo::find_node_at_offset,
24 SyntaxNode, TextRange, TextSize, T,
27 use crate::{FilePosition, NavigationTarget, TryToNav};
29 #[derive(Debug, Clone)]
30 pub struct ReferenceSearchResult {
31 pub declaration: Option<Declaration>,
32 pub references: FxHashMap<FileId, Vec<(TextRange, Option<ReferenceCategory>)>>,
35 #[derive(Debug, Clone)]
36 pub struct Declaration {
37 pub nav: NavigationTarget,
41 // Feature: Find All References
43 // Shows all references of the item at the cursor location
46 // | Editor | Shortcut
48 // | VS Code | kbd:[Shift+Alt+F12]
51 // image::https://user-images.githubusercontent.com/48062697/113020670-b7c34f00-917a-11eb-8003-370ac5f2b3cb.gif[]
52 pub(crate) fn find_all_refs(
53 sema: &Semantics<'_, RootDatabase>,
54 position: FilePosition,
55 search_scope: Option<SearchScope>,
56 ) -> Option<Vec<ReferenceSearchResult>> {
57 let _p = profile::span("find_all_refs");
58 let syntax = sema.parse(position.file_id).syntax().clone();
59 let make_searcher = |literal_search: bool| {
60 move |def: Definition| {
61 let declaration = match def {
62 Definition::Module(module) => {
63 Some(NavigationTarget::from_module_to_decl(sema.db, module))
65 def => def.try_to_nav(sema.db),
68 let decl_range = nav.focus_or_full_range();
70 is_mut: decl_mutability(&def, sema.parse(nav.file_id).syntax(), decl_range),
75 def.usages(sema).set_scope(search_scope.clone()).include_self_refs().all();
78 retain_adt_literal_usages(&mut usages, def, sema);
81 let references = usages
83 .map(|(file_id, refs)| {
87 .map(|file_ref| (file_ref.range, file_ref.category))
93 ReferenceSearchResult { declaration, references }
97 match name_for_constructor_search(&syntax, position) {
99 let def = match NameClass::classify(sema, &name)? {
100 NameClass::Definition(it) | NameClass::ConstReference(it) => it,
101 NameClass::PatFieldShorthand { local_def: _, field_ref } => {
102 Definition::Field(field_ref)
105 Some(vec![make_searcher(true)(def)])
108 let search = make_searcher(false);
109 Some(find_defs(sema, &syntax, position.offset)?.map(search).collect())
114 pub(crate) fn find_defs<'a>(
115 sema: &'a Semantics<'_, RootDatabase>,
118 ) -> Option<impl Iterator<Item = Definition> + 'a> {
119 let token = syntax.token_at_offset(offset).find(|t| {
122 IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] | T![Self]
126 sema.descend_into_macros_with_same_text(token)
128 .filter_map(|it| ast::NameLike::cast(it.parent()?))
129 .filter_map(move |name_like| {
130 let def = match name_like {
131 ast::NameLike::NameRef(name_ref) => {
132 match NameRefClass::classify(sema, &name_ref)? {
133 NameRefClass::Definition(def) => def,
134 NameRefClass::FieldShorthand { local_ref, field_ref: _ } => {
135 Definition::Local(local_ref)
139 ast::NameLike::Name(name) => match NameClass::classify(sema, &name)? {
140 NameClass::Definition(it) | NameClass::ConstReference(it) => it,
141 NameClass::PatFieldShorthand { local_def, field_ref: _ } => {
142 Definition::Local(local_def)
145 ast::NameLike::Lifetime(lifetime) => {
146 NameRefClass::classify_lifetime(sema, &lifetime)
147 .and_then(|class| match class {
148 NameRefClass::Definition(it) => Some(it),
152 NameClass::classify_lifetime(sema, &lifetime)
153 .and_then(NameClass::defined)
162 pub(crate) fn decl_mutability(def: &Definition, syntax: &SyntaxNode, range: TextRange) -> bool {
164 Definition::Local(_) | Definition::Field(_) => {}
168 match find_node_at_offset::<ast::LetStmt>(syntax, range.start()) {
169 Some(stmt) if stmt.initializer().is_some() => match stmt.pat() {
170 Some(ast::Pat::IdentPat(it)) => it.mut_token().is_some(),
177 /// Filter out all non-literal usages for adt-defs
178 fn retain_adt_literal_usages(
179 usages: &mut UsageSearchResult,
181 sema: &Semantics<'_, RootDatabase>,
183 let refs = usages.references.values_mut();
185 Definition::Adt(hir::Adt::Enum(enum_)) => {
187 it.retain(|reference| {
191 .map_or(false, |name_ref| is_enum_lit_name_ref(sema, enum_, name_ref))
194 usages.references.retain(|_, it| !it.is_empty());
196 Definition::Adt(_) | Definition::Variant(_) => {
198 it.retain(|reference| reference.name.as_name_ref().map_or(false, is_lit_name_ref))
200 usages.references.retain(|_, it| !it.is_empty());
206 /// Returns `Some` if the cursor is at a position for an item to search for all its constructor/literal usages
207 fn name_for_constructor_search(syntax: &SyntaxNode, position: FilePosition) -> Option<ast::Name> {
208 let token = syntax.token_at_offset(position.offset).right_biased()?;
209 let token_parent = token.parent()?;
210 let kind = token.kind();
212 ast::Struct::cast(token_parent)
213 .filter(|struct_| struct_.field_list().is_none())
214 .and_then(|struct_| struct_.name())
215 } else if kind == T!['{'] {
218 ast::RecordFieldList(rfl) => match_ast! {
219 match (rfl.syntax().parent()?) {
220 ast::Variant(it) => it.name(),
221 ast::Struct(it) => it.name(),
222 ast::Union(it) => it.name(),
226 ast::VariantList(vl) => ast::Enum::cast(vl.syntax().parent()?)?.name(),
230 } else if kind == T!['('] {
231 let tfl = ast::TupleFieldList::cast(token_parent)?;
233 match (tfl.syntax().parent()?) {
234 ast::Variant(it) => it.name(),
235 ast::Struct(it) => it.name(),
244 fn is_enum_lit_name_ref(
245 sema: &Semantics<'_, RootDatabase>,
247 name_ref: &ast::NameRef,
249 let path_is_variant_of_enum = |path: ast::Path| {
251 sema.resolve_path(&path),
252 Some(PathResolution::Def(hir::ModuleDef::Variant(variant)))
253 if variant.parent_enum(sema.db) == enum_
259 .find_map(|ancestor| {
262 ast::PathExpr(path_expr) => path_expr.path().map(path_is_variant_of_enum),
263 ast::RecordExpr(record_expr) => record_expr.path().map(path_is_variant_of_enum),
271 fn path_ends_with(path: Option<ast::Path>, name_ref: &ast::NameRef) -> bool {
272 path.and_then(|path| path.segment())
273 .and_then(|segment| segment.name_ref())
274 .map_or(false, |segment| segment == *name_ref)
277 fn is_lit_name_ref(name_ref: &ast::NameRef) -> bool {
278 name_ref.syntax().ancestors().find_map(|ancestor| {
281 ast::PathExpr(path_expr) => Some(path_ends_with(path_expr.path(), name_ref)),
282 ast::RecordExpr(record_expr) => Some(path_ends_with(record_expr.path(), name_ref)),
291 use expect_test::{expect, Expect};
292 use ide_db::{base_db::FileId, search::ReferenceCategory};
295 use crate::{fixture, SearchScope};
298 fn test_struct_literal_after_space() {
309 f = Foo {a: Foo::f()};
313 Foo Struct FileId(0) 0..26 7..10
321 fn test_struct_literal_before_space() {
331 Foo Struct FileId(0) 0..13 7..10
340 fn test_struct_literal_with_generic_type() {
350 Foo Struct FileId(0) 0..16 7..10
358 fn test_struct_literal_for_tuple() {
369 Foo Struct FileId(0) 0..16 7..10
377 fn test_struct_literal_for_union() {
390 Foo Union FileId(0) 0..24 6..9
398 fn test_enum_after_space() {
414 Foo Enum FileId(0) 0..37 5..8
424 fn test_variant_record_after_space() {
434 f = Foo::A { n: 92 };
438 A Variant FileId(0) 15..27 15..16
445 fn test_variant_tuple_before_paren() {
459 A Variant FileId(0) 15..21 15..16
467 fn test_enum_before_space() {
480 Foo Enum FileId(0) 0..26 5..8
489 fn test_enum_with_generic_type() {
502 Foo Enum FileId(0) 0..32 5..8
510 fn test_enum_for_tuple() {
523 Foo Enum FileId(0) 0..33 5..8
531 fn test_find_all_refs_for_local() {
546 i Local FileId(0) 20..25 24..25 Write
548 FileId(0) 50..51 Write
549 FileId(0) 54..55 Read
550 FileId(0) 76..77 Write
551 FileId(0) 94..95 Write
557 fn search_filters_by_range() {
570 spam Local FileId(0) 19..23 19..23
572 FileId(0) 34..38 Read
573 FileId(0) 41..45 Read
579 fn test_find_all_refs_for_param_inside() {
582 fn foo(i : u32) -> u32 { i$0 }
585 i ValueParam FileId(0) 7..8 7..8
587 FileId(0) 25..26 Read
593 fn test_find_all_refs_for_fn_param() {
596 fn foo(i$0 : u32) -> u32 { i }
599 i ValueParam FileId(0) 7..8 7..8
601 FileId(0) 25..26 Read
607 fn test_find_all_refs_field_name() {
620 spam Field FileId(0) 17..30 21..25
622 FileId(0) 67..71 Read
628 fn test_find_all_refs_impl_item_name() {
637 f Function FileId(0) 27..43 30..31
645 fn test_find_all_refs_enum_var_name() {
655 B Variant FileId(0) 22..23 22..23
663 fn test_find_all_refs_enum_var_field() {
673 field Field FileId(0) 26..35 26..31
681 fn test_find_all_refs_two_modules() {
689 let i = foo::Foo { n: 5 };
700 let i = bar::Bar { n: 5 };
711 let i = foo::Foo$0 { n: 5 };
715 Foo Struct FileId(1) 17..51 28..31
724 fn test_find_all_refs_decl_module() {
733 let i = Foo { n: 5 };
742 foo Module FileId(0) 0..8 4..7
750 fn test_find_all_refs_decl_module_on_self() {
760 foo Module FileId(0) 0..8 4..7
768 fn test_find_all_refs_decl_module_on_self_crate_root() {
775 Module FileId(0) 0..10
783 fn test_find_all_refs_super_mod_vis() {
794 let i = Foo { n: 5 };
798 pub(super) struct Foo$0 {
803 Foo Struct FileId(2) 0..41 18..21
812 fn test_find_all_refs_with_scope() {
821 fn f() { super::quux(); }
824 fn f() { super::quux(); }
831 quux Function FileId(0) 19..35 26..30
840 Some(SearchScope::single_file(FileId(2))),
842 quux Function FileId(0) 19..35 26..30
850 fn test_find_all_refs_macro_def() {
854 macro_rules! m1$0 { () => (()) }
862 m1 Macro FileId(0) 0..46 29..31
871 fn test_basic_highlight_read_write() {
880 i Local FileId(0) 19..24 23..24 Write
882 FileId(0) 34..35 Write
883 FileId(0) 38..39 Read
889 fn test_basic_highlight_field_read_write() {
902 f Field FileId(0) 15..21 15..16
904 FileId(0) 55..56 Read
905 FileId(0) 68..69 Write
911 fn test_basic_highlight_decl_no_write() {
920 i Local FileId(0) 19..20 19..20
922 FileId(0) 26..27 Write
928 fn test_find_struct_function_refs_outside_module() {
935 pub fn new$0() -> Foo { Foo }
940 let _f = foo::Foo::new();
944 new Function FileId(0) 54..81 61..64
952 fn test_find_all_refs_nested_module() {
966 f Function FileId(0) 22..31 25..26
975 fn test_find_all_refs_struct_pat() {
989 field Field FileId(0) 15..24 15..20
991 FileId(0) 68..73 Read
997 fn test_find_all_refs_enum_var_pat() {
1008 En::Variant { field } => {}
1013 field Field FileId(0) 32..41 32..37
1015 FileId(0) 102..107 Read
1021 fn test_find_all_refs_enum_var_privacy() {
1033 m::En::Variant { field: 0 }
1037 field Field FileId(0) 56..65 56..61
1039 FileId(0) 125..130 Read
1045 fn test_find_self_refs() {
1048 struct Foo { bar: i32 }
1062 self SelfParam FileId(0) 47..51 47..51
1064 FileId(0) 71..75 Read
1065 FileId(0) 152..156 Read
1071 fn test_find_self_refs_decl() {
1074 struct Foo { bar: i32 }
1083 self SelfParam FileId(0) 47..51 47..51
1085 FileId(0) 63..67 Read
1090 fn check(ra_fixture: &str, expect: Expect) {
1091 check_with_scope(ra_fixture, None, expect)
1094 fn check_with_scope(ra_fixture: &str, search_scope: Option<SearchScope>, expect: Expect) {
1095 let (analysis, pos) = fixture::position(ra_fixture);
1096 let refs = analysis.find_all_refs(pos, search_scope).unwrap().unwrap();
1098 let mut actual = String::new();
1102 if let Some(decl) = refs.declaration {
1103 format_to!(actual, "{}", decl.nav.debug_render());
1105 format_to!(actual, " {:?}", ReferenceCategory::Write)
1110 for (file_id, references) in &refs.references {
1111 for (range, access) in references {
1112 format_to!(actual, "{:?} {:?}", file_id, range);
1113 if let Some(access) = access {
1114 format_to!(actual, " {:?}", access);
1120 if refs.references.is_empty() {
1121 actual += "(no references)\n";
1124 expect.assert_eq(actual.trim_start())
1128 fn test_find_lifetimes_function() {
1132 impl<'a> Foo<'a> for &'a () {}
1133 fn foo<'a, 'b: 'a>(x: &'a$0 ()) -> &'a () where &'a (): Foo<'a> {
1134 fn bar<'a>(_: &'a ()) {}
1139 'a LifetimeParam FileId(0) 55..57 55..57
1151 fn test_find_lifetimes_type_alias() {
1154 type Foo<'a, T> where T: 'a$0 = &'a T;
1157 'a LifetimeParam FileId(0) 9..11 9..11
1166 fn test_find_lifetimes_trait_impl() {
1172 impl<'a> Foo<'a> for &'a () {
1173 fn foo() -> &'a$0 () {
1179 'a LifetimeParam FileId(0) 47..49 47..49
1189 fn test_map_range_to_original() {
1192 macro_rules! foo {($i:ident) => {$i} }
1199 a Local FileId(0) 59..60 59..60
1201 FileId(0) 80..81 Read
1207 fn test_map_range_to_original_ref() {
1210 macro_rules! foo {($i:ident) => {$i} }
1217 a Local FileId(0) 59..60 59..60
1219 FileId(0) 80..81 Read
1225 fn test_find_labels() {
1228 fn foo<'a>() -> &'a () {
1238 'a Label FileId(0) 29..32 29..31
1247 fn test_find_const_param() {
1250 fn foo<const FOO$0: usize>() -> usize {
1255 FOO ConstParam FileId(0) 7..23 13..16
1266 trait Foo$0 where Self: {}
1271 Foo Trait FileId(0) 0..24 6..9
1279 fn test_trait_self() {
1282 trait Foo where Self$0 {
1289 Self TypeParam FileId(0) 6..9 6..9
1303 impl Foo where Self: {
1308 Foo Struct FileId(0) 0..11 7..10
1319 impl Foo where Self: {
1324 impl Impl FileId(0) 13..57 18..21
1333 fn test_self_variant_with_payload() {
1341 Self::Bar$0() => (),
1348 Bar Variant FileId(0) 11..16 11..14
1356 fn test_attr_differs_from_fn_with_same_name() {
1365 test Function FileId(0) 0..33 11..15
1373 fn test_const_in_pattern() {
1376 const A$0: i32 = 42;
1387 A Const FileId(0) 0..18 6..7
1398 fn test_primitives() {
1401 fn foo(_: bool) -> bo$0ol { true }
1411 fn test_transitive() {
1414 //- /level3.rs new_source_root:local crate:level3
1416 //- /level2.rs new_source_root:local crate:level2 deps:level3
1417 pub use level3::Foo;
1418 //- /level1.rs new_source_root:local crate:level1 deps:level2
1419 pub use level2::Foo;
1420 //- /level0.rs new_source_root:local crate:level0 deps:level1
1421 pub use level1::Foo;
1424 Foo Struct FileId(0) 0..15 11..14
1434 fn test_decl_macro_references() {
1437 //- /lib.rs crate:lib
1445 macro_rules! foo$0 {
1446 () => {struct Foo;};
1450 //- /other.rs crate:other deps:lib new_source_root:local
1454 foo Macro FileId(1) 0..61 29..32
1464 fn macro_doesnt_reference_attribute_on_call() {
1471 #[proc_macro_test::attr_noop]
1476 m Macro FileId(0) 0..32 13..14
1505 func Function FileId(0) 137..146 140..144
1510 func Function FileId(0) 137..146 140..144
1518 fn attr_expanded() {
1521 //- proc_macros: identity
1522 #[proc_macros::identity]
1528 func Function FileId(0) 25..50 28..32
1536 fn attr_assoc_item() {
1539 //- proc_macros: identity
1542 #[proc_macros::identity]
1549 func Function FileId(0) 48..87 51..55
1556 // FIXME: import is classified as function
1561 //- proc_macros: identity
1562 use proc_macros::identity;
1564 #[proc_macros::$0identity]
1568 identity Attribute FileId(1) 1..107 32..40
1575 #![crate_type="proc-macro"]
1576 #[proc_macro_attribute]
1580 func Attribute FileId(0) 28..64 55..59
1587 // FIXME: import is classified as function
1592 //- proc_macros: mirror
1593 use proc_macros::mirror;
1598 mirror Macro FileId(1) 1..77 22..28
1609 //- proc_macros: derive_identity
1610 //- minicore: derive
1611 use proc_macros::DeriveIdentity;
1613 #[derive(proc_macros::DeriveIdentity$0)]
1617 derive_identity Derive FileId(2) 1..107 45..60
1625 #![crate_type="proc-macro"]
1626 #[proc_macro_derive(Derive, attributes(x))]
1627 pub fn deri$0ve(_stream: TokenStream) -> TokenStream {}
1630 derive Derive FileId(0) 28..125 79..85