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},
19 use rustc_hash::FxHashMap;
21 algo::find_node_at_offset,
23 match_ast, AstNode, SyntaxNode, TextRange, TextSize, T,
26 use crate::{FilePosition, NavigationTarget, TryToNav};
28 #[derive(Debug, Clone)]
29 pub struct ReferenceSearchResult {
30 pub declaration: Option<Declaration>,
31 pub references: FxHashMap<FileId, Vec<(TextRange, Option<ReferenceCategory>)>>,
34 #[derive(Debug, Clone)]
35 pub struct Declaration {
36 pub nav: NavigationTarget,
40 // Feature: Find All References
42 // Shows all references of the item at the cursor location
45 // | Editor | Shortcut
47 // | VS Code | kbd:[Shift+Alt+F12]
50 // image::https://user-images.githubusercontent.com/48062697/113020670-b7c34f00-917a-11eb-8003-370ac5f2b3cb.gif[]
51 pub(crate) fn find_all_refs(
52 sema: &Semantics<RootDatabase>,
53 position: FilePosition,
54 search_scope: Option<SearchScope>,
55 ) -> Option<Vec<ReferenceSearchResult>> {
56 let _p = profile::span("find_all_refs");
57 let syntax = sema.parse(position.file_id).syntax().clone();
58 let make_searcher = |literal_search: bool| {
59 move |def: Definition| {
61 def.usages(sema).set_scope(search_scope.clone()).include_self_refs().all();
62 let declaration = match def {
63 Definition::Module(module) => {
64 Some(NavigationTarget::from_module_to_decl(sema.db, module))
66 def => def.try_to_nav(sema.db),
69 let decl_range = nav.focus_or_full_range();
71 is_mut: decl_mutability(&def, sema.parse(nav.file_id).syntax(), decl_range),
76 retain_adt_literal_usages(&mut usages, def, sema);
79 let references = usages
81 .map(|(file_id, refs)| {
85 .map(|file_ref| (file_ref.range, file_ref.category))
91 ReferenceSearchResult { declaration, references }
95 match name_for_constructor_search(&syntax, position) {
97 let def = match NameClass::classify(sema, &name)? {
98 NameClass::Definition(it) | NameClass::ConstReference(it) => it,
99 NameClass::PatFieldShorthand { local_def: _, field_ref } => {
100 Definition::Field(field_ref)
103 Some(vec![make_searcher(true)(def)])
106 let search = make_searcher(false);
107 Some(find_defs(sema, &syntax, position.offset).into_iter().map(search).collect())
112 pub(crate) fn find_defs<'a>(
113 sema: &'a Semantics<RootDatabase>,
116 ) -> impl Iterator<Item = Definition> + 'a {
117 sema.find_nodes_at_offset_with_descend(syntax, offset).filter_map(move |name_like| {
118 let def = match name_like {
119 ast::NameLike::NameRef(name_ref) => match NameRefClass::classify(sema, &name_ref)? {
120 NameRefClass::Definition(def) => def,
121 NameRefClass::FieldShorthand { local_ref, field_ref: _ } => {
122 Definition::Local(local_ref)
125 ast::NameLike::Name(name) => match NameClass::classify(sema, &name)? {
126 NameClass::Definition(it) | NameClass::ConstReference(it) => it,
127 NameClass::PatFieldShorthand { local_def, field_ref: _ } => {
128 Definition::Local(local_def)
131 ast::NameLike::Lifetime(lifetime) => NameRefClass::classify_lifetime(sema, &lifetime)
132 .and_then(|class| match class {
133 NameRefClass::Definition(it) => Some(it),
137 NameClass::classify_lifetime(sema, &lifetime).and_then(NameClass::defined)
144 pub(crate) fn decl_mutability(def: &Definition, syntax: &SyntaxNode, range: TextRange) -> bool {
146 Definition::Local(_) | Definition::Field(_) => {}
150 match find_node_at_offset::<ast::LetStmt>(syntax, range.start()) {
151 Some(stmt) if stmt.initializer().is_some() => match stmt.pat() {
152 Some(ast::Pat::IdentPat(it)) => it.mut_token().is_some(),
159 /// Filter out all non-literal usages for adt-defs
160 fn retain_adt_literal_usages(
161 usages: &mut UsageSearchResult,
163 sema: &Semantics<RootDatabase>,
165 let refs = usages.references.values_mut();
167 Definition::Adt(hir::Adt::Enum(enum_)) => {
169 it.retain(|reference| {
173 .map_or(false, |name_ref| is_enum_lit_name_ref(sema, enum_, name_ref))
176 usages.references.retain(|_, it| !it.is_empty());
178 Definition::Adt(_) | Definition::Variant(_) => {
180 it.retain(|reference| reference.name.as_name_ref().map_or(false, is_lit_name_ref))
182 usages.references.retain(|_, it| !it.is_empty());
188 /// Returns `Some` if the cursor is at a position for an item to search for all its constructor/literal usages
189 fn name_for_constructor_search(syntax: &SyntaxNode, position: FilePosition) -> Option<ast::Name> {
190 let token = syntax.token_at_offset(position.offset).right_biased()?;
191 let token_parent = token.parent()?;
192 let kind = token.kind();
194 ast::Struct::cast(token_parent)
195 .filter(|struct_| struct_.field_list().is_none())
196 .and_then(|struct_| struct_.name())
197 } else if kind == T!['{'] {
200 ast::RecordFieldList(rfl) => match_ast! {
201 match (rfl.syntax().parent()?) {
202 ast::Variant(it) => it.name(),
203 ast::Struct(it) => it.name(),
204 ast::Union(it) => it.name(),
208 ast::VariantList(vl) => ast::Enum::cast(vl.syntax().parent()?)?.name(),
212 } else if kind == T!['('] {
213 let tfl = ast::TupleFieldList::cast(token_parent)?;
215 match (tfl.syntax().parent()?) {
216 ast::Variant(it) => it.name(),
217 ast::Struct(it) => it.name(),
226 fn is_enum_lit_name_ref(
227 sema: &Semantics<RootDatabase>,
229 name_ref: &ast::NameRef,
231 let path_is_variant_of_enum = |path: ast::Path| {
233 sema.resolve_path(&path),
234 Some(PathResolution::Def(hir::ModuleDef::Variant(variant)))
235 if variant.parent_enum(sema.db) == enum_
241 .find_map(|ancestor| {
244 ast::PathExpr(path_expr) => path_expr.path().map(path_is_variant_of_enum),
245 ast::RecordExpr(record_expr) => record_expr.path().map(path_is_variant_of_enum),
253 fn path_ends_with(path: Option<ast::Path>, name_ref: &ast::NameRef) -> bool {
254 path.and_then(|path| path.segment())
255 .and_then(|segment| segment.name_ref())
256 .map_or(false, |segment| segment == *name_ref)
259 fn is_lit_name_ref(name_ref: &ast::NameRef) -> bool {
260 name_ref.syntax().ancestors().find_map(|ancestor| {
263 ast::PathExpr(path_expr) => Some(path_ends_with(path_expr.path(), name_ref)),
264 ast::RecordExpr(record_expr) => Some(path_ends_with(record_expr.path(), name_ref)),
273 use expect_test::{expect, Expect};
274 use ide_db::{base_db::FileId, search::ReferenceCategory};
277 use crate::{fixture, SearchScope};
280 fn test_struct_literal_after_space() {
291 f = Foo {a: Foo::f()};
295 Foo Struct FileId(0) 0..26 7..10
303 fn test_struct_literal_before_space() {
313 Foo Struct FileId(0) 0..13 7..10
322 fn test_struct_literal_with_generic_type() {
332 Foo Struct FileId(0) 0..16 7..10
340 fn test_struct_literal_for_tuple() {
351 Foo Struct FileId(0) 0..16 7..10
359 fn test_struct_literal_for_union() {
372 Foo Union FileId(0) 0..24 6..9
380 fn test_enum_after_space() {
396 Foo Enum FileId(0) 0..37 5..8
406 fn test_variant_record_after_space() {
416 f = Foo::A { n: 92 };
420 A Variant FileId(0) 15..27 15..16
427 fn test_variant_tuple_before_paren() {
441 A Variant FileId(0) 15..21 15..16
449 fn test_enum_before_space() {
462 Foo Enum FileId(0) 0..26 5..8
471 fn test_enum_with_generic_type() {
484 Foo Enum FileId(0) 0..32 5..8
492 fn test_enum_for_tuple() {
505 Foo Enum FileId(0) 0..33 5..8
513 fn test_find_all_refs_for_local() {
528 i Local FileId(0) 20..25 24..25 Write
530 FileId(0) 50..51 Write
531 FileId(0) 54..55 Read
532 FileId(0) 76..77 Write
533 FileId(0) 94..95 Write
539 fn search_filters_by_range() {
552 spam Local FileId(0) 19..23 19..23
554 FileId(0) 34..38 Read
555 FileId(0) 41..45 Read
561 fn test_find_all_refs_for_param_inside() {
564 fn foo(i : u32) -> u32 { i$0 }
567 i ValueParam FileId(0) 7..8 7..8
569 FileId(0) 25..26 Read
575 fn test_find_all_refs_for_fn_param() {
578 fn foo(i$0 : u32) -> u32 { i }
581 i ValueParam FileId(0) 7..8 7..8
583 FileId(0) 25..26 Read
589 fn test_find_all_refs_field_name() {
602 spam Field FileId(0) 17..30 21..25
604 FileId(0) 67..71 Read
610 fn test_find_all_refs_impl_item_name() {
619 f Function FileId(0) 27..43 30..31
627 fn test_find_all_refs_enum_var_name() {
637 B Variant FileId(0) 22..23 22..23
645 fn test_find_all_refs_enum_var_field() {
655 field Field FileId(0) 26..35 26..31
663 fn test_find_all_refs_two_modules() {
671 let i = foo::Foo { n: 5 };
682 let i = bar::Bar { n: 5 };
693 let i = foo::Foo$0 { n: 5 };
697 Foo Struct FileId(1) 17..51 28..31
706 fn test_find_all_refs_decl_module() {
715 let i = Foo { n: 5 };
724 foo Module FileId(0) 0..8 4..7
732 fn test_find_all_refs_decl_module_on_self() {
742 foo Module FileId(0) 0..8 4..7
750 fn test_find_all_refs_decl_module_on_self_crate_root() {
757 Module FileId(0) 0..10
765 fn test_find_all_refs_super_mod_vis() {
776 let i = Foo { n: 5 };
780 pub(super) struct Foo$0 {
785 Foo Struct FileId(2) 0..41 18..21
794 fn test_find_all_refs_with_scope() {
803 fn f() { super::quux(); }
806 fn f() { super::quux(); }
813 quux Function FileId(0) 19..35 26..30
822 Some(SearchScope::single_file(FileId(2))),
824 quux Function FileId(0) 19..35 26..30
832 fn test_find_all_refs_macro_def() {
836 macro_rules! m1$0 { () => (()) }
844 m1 Macro FileId(0) 0..46 29..31
853 fn test_basic_highlight_read_write() {
862 i Local FileId(0) 19..24 23..24 Write
864 FileId(0) 34..35 Write
865 FileId(0) 38..39 Read
871 fn test_basic_highlight_field_read_write() {
884 f Field FileId(0) 15..21 15..16
886 FileId(0) 55..56 Read
887 FileId(0) 68..69 Write
893 fn test_basic_highlight_decl_no_write() {
902 i Local FileId(0) 19..20 19..20
904 FileId(0) 26..27 Write
910 fn test_find_struct_function_refs_outside_module() {
917 pub fn new$0() -> Foo { Foo }
922 let _f = foo::Foo::new();
926 new Function FileId(0) 54..81 61..64
934 fn test_find_all_refs_nested_module() {
948 f Function FileId(0) 22..31 25..26
957 fn test_find_all_refs_struct_pat() {
971 field Field FileId(0) 15..24 15..20
973 FileId(0) 68..73 Read
979 fn test_find_all_refs_enum_var_pat() {
990 En::Variant { field } => {}
995 field Field FileId(0) 32..41 32..37
997 FileId(0) 102..107 Read
1003 fn test_find_all_refs_enum_var_privacy() {
1015 m::En::Variant { field: 0 }
1019 field Field FileId(0) 56..65 56..61
1021 FileId(0) 125..130 Read
1027 fn test_find_self_refs() {
1030 struct Foo { bar: i32 }
1044 self SelfParam FileId(0) 47..51 47..51
1046 FileId(0) 71..75 Read
1047 FileId(0) 152..156 Read
1053 fn test_find_self_refs_decl() {
1056 struct Foo { bar: i32 }
1065 self SelfParam FileId(0) 47..51 47..51
1067 FileId(0) 63..67 Read
1072 fn check(ra_fixture: &str, expect: Expect) {
1073 check_with_scope(ra_fixture, None, expect)
1076 fn check_with_scope(ra_fixture: &str, search_scope: Option<SearchScope>, expect: Expect) {
1077 let (analysis, pos) = fixture::position(ra_fixture);
1078 let refs = analysis.find_all_refs(pos, search_scope).unwrap().unwrap();
1080 let mut actual = String::new();
1084 if let Some(decl) = refs.declaration {
1085 format_to!(actual, "{}", decl.nav.debug_render());
1087 format_to!(actual, " {:?}", ReferenceCategory::Write)
1092 for (file_id, references) in &refs.references {
1093 for (range, access) in references {
1094 format_to!(actual, "{:?} {:?}", file_id, range);
1095 if let Some(access) = access {
1096 format_to!(actual, " {:?}", access);
1102 if refs.references.is_empty() {
1103 actual += "(no references)\n";
1106 expect.assert_eq(actual.trim_start())
1110 fn test_find_lifetimes_function() {
1114 impl<'a> Foo<'a> for &'a () {}
1115 fn foo<'a, 'b: 'a>(x: &'a$0 ()) -> &'a () where &'a (): Foo<'a> {
1116 fn bar<'a>(_: &'a ()) {}
1121 'a LifetimeParam FileId(0) 55..57 55..57
1133 fn test_find_lifetimes_type_alias() {
1136 type Foo<'a, T> where T: 'a$0 = &'a T;
1139 'a LifetimeParam FileId(0) 9..11 9..11
1148 fn test_find_lifetimes_trait_impl() {
1154 impl<'a> Foo<'a> for &'a () {
1155 fn foo() -> &'a$0 () {
1161 'a LifetimeParam FileId(0) 47..49 47..49
1171 fn test_map_range_to_original() {
1174 macro_rules! foo {($i:ident) => {$i} }
1181 a Local FileId(0) 59..60 59..60
1183 FileId(0) 80..81 Read
1189 fn test_map_range_to_original_ref() {
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_find_labels() {
1210 fn foo<'a>() -> &'a () {
1220 'a Label FileId(0) 29..32 29..31
1229 fn test_find_const_param() {
1232 fn foo<const FOO$0: usize>() -> usize {
1237 FOO ConstParam FileId(0) 7..23 13..16
1248 trait Foo$0 where Self: {}
1253 Foo Trait FileId(0) 0..24 6..9
1261 fn test_trait_self() {
1264 trait Foo where Self$0 {
1271 Self TypeParam FileId(0) 6..9 6..9
1285 impl Foo where Self: {
1290 Foo Struct FileId(0) 0..11 7..10
1301 impl Foo where Self: {
1306 impl Impl FileId(0) 13..57 18..21
1315 fn test_self_variant_with_payload() {
1323 Self::Bar$0() => (),
1330 Bar Variant FileId(0) 11..16 11..14
1338 fn test_attr_differs_from_fn_with_same_name() {
1347 test Function FileId(0) 0..33 11..15
1355 fn test_const_in_pattern() {
1358 const A$0: i32 = 42;
1369 A Const FileId(0) 0..18 6..7
1380 fn test_primitives() {
1383 fn foo(_: bool) -> bo$0ol { true }
1393 fn test_transitive() {
1396 //- /level3.rs new_source_root:local crate:level3
1398 //- /level2.rs new_source_root:local crate:level2 deps:level3
1399 pub use level3::Foo;
1400 //- /level1.rs new_source_root:local crate:level1 deps:level2
1401 pub use level2::Foo;
1402 //- /level0.rs new_source_root:local crate:level0 deps:level1
1403 pub use level1::Foo;
1406 Foo Struct FileId(0) 0..15 11..14
1416 fn test_decl_macro_references() {
1419 //- /lib.rs crate:lib
1427 macro_rules! foo$0 {
1428 () => {struct Foo;};
1432 //- /other.rs crate:other deps:lib new_source_root:local
1436 foo Macro FileId(1) 0..61 29..32
1446 fn macro_doesnt_reference_attribute_on_call() {
1453 #[proc_macro_test::attr_noop]
1458 m Macro FileId(0) 0..32 13..14
1487 func Function FileId(0) 137..146 140..144
1492 func Function FileId(0) 137..146 140..144
1500 fn attr_expanded() {
1503 //- proc_macros: identity
1505 #[proc_macros::identity]
1511 func Function FileId(0) 26..51 29..33
1519 fn attr_assoc_item() {
1522 //- proc_macros: identity
1525 #[proc_macros::identity]
1532 func Function FileId(0) 48..87 51..55