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 itertools::Itertools;
20 use stdx::hash::NoHashHashMap;
22 algo::find_node_at_offset,
26 SyntaxNode, TextRange, TextSize, T,
29 use crate::{FilePosition, NavigationTarget, TryToNav};
31 #[derive(Debug, Clone)]
32 pub struct ReferenceSearchResult {
33 pub declaration: Option<Declaration>,
34 pub references: NoHashHashMap<FileId, Vec<(TextRange, Option<ReferenceCategory>)>>,
37 #[derive(Debug, Clone)]
38 pub struct Declaration {
39 pub nav: NavigationTarget,
43 // Feature: Find All References
45 // Shows all references of the item at the cursor location
48 // | Editor | Shortcut
50 // | VS Code | kbd:[Shift+Alt+F12]
53 // image::https://user-images.githubusercontent.com/48062697/113020670-b7c34f00-917a-11eb-8003-370ac5f2b3cb.gif[]
54 pub(crate) fn find_all_refs(
55 sema: &Semantics<'_, RootDatabase>,
56 position: FilePosition,
57 search_scope: Option<SearchScope>,
58 ) -> Option<Vec<ReferenceSearchResult>> {
59 let _p = profile::span("find_all_refs");
60 let syntax = sema.parse(position.file_id).syntax().clone();
61 let make_searcher = |literal_search: bool| {
62 move |def: Definition| {
63 let declaration = match def {
64 Definition::Module(module) => {
65 Some(NavigationTarget::from_module_to_decl(sema.db, module))
67 def => def.try_to_nav(sema.db),
70 let decl_range = nav.focus_or_full_range();
72 is_mut: decl_mutability(&def, sema.parse(nav.file_id).syntax(), decl_range),
77 def.usages(sema).set_scope(search_scope.clone()).include_self_refs().all();
80 retain_adt_literal_usages(&mut usages, def, sema);
83 let references = usages
85 .map(|(file_id, refs)| {
89 .map(|file_ref| (file_ref.range, file_ref.category))
96 ReferenceSearchResult { declaration, references }
100 match name_for_constructor_search(&syntax, position) {
102 let def = match NameClass::classify(sema, &name)? {
103 NameClass::Definition(it) | NameClass::ConstReference(it) => it,
104 NameClass::PatFieldShorthand { local_def: _, field_ref } => {
105 Definition::Field(field_ref)
108 Some(vec![make_searcher(true)(def)])
111 let search = make_searcher(false);
112 Some(find_defs(sema, &syntax, position.offset)?.map(search).collect())
117 pub(crate) fn find_defs<'a>(
118 sema: &'a Semantics<'_, RootDatabase>,
121 ) -> Option<impl Iterator<Item = Definition> + 'a> {
122 let token = syntax.token_at_offset(offset).find(|t| {
125 IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] | T![Self]
129 sema.descend_into_macros_with_same_text(token)
131 .filter_map(|it| ast::NameLike::cast(it.parent()?))
132 .filter_map(move |name_like| {
133 let def = match name_like {
134 ast::NameLike::NameRef(name_ref) => {
135 match NameRefClass::classify(sema, &name_ref)? {
136 NameRefClass::Definition(def) => def,
137 NameRefClass::FieldShorthand { local_ref, field_ref: _ } => {
138 Definition::Local(local_ref)
142 ast::NameLike::Name(name) => match NameClass::classify(sema, &name)? {
143 NameClass::Definition(it) | NameClass::ConstReference(it) => it,
144 NameClass::PatFieldShorthand { local_def, field_ref: _ } => {
145 Definition::Local(local_def)
148 ast::NameLike::Lifetime(lifetime) => {
149 NameRefClass::classify_lifetime(sema, &lifetime)
150 .and_then(|class| match class {
151 NameRefClass::Definition(it) => Some(it),
155 NameClass::classify_lifetime(sema, &lifetime)
156 .and_then(NameClass::defined)
165 pub(crate) fn decl_mutability(def: &Definition, syntax: &SyntaxNode, range: TextRange) -> bool {
167 Definition::Local(_) | Definition::Field(_) => {}
171 match find_node_at_offset::<ast::LetStmt>(syntax, range.start()) {
172 Some(stmt) if stmt.initializer().is_some() => match stmt.pat() {
173 Some(ast::Pat::IdentPat(it)) => it.mut_token().is_some(),
180 /// Filter out all non-literal usages for adt-defs
181 fn retain_adt_literal_usages(
182 usages: &mut UsageSearchResult,
184 sema: &Semantics<'_, RootDatabase>,
186 let refs = usages.references.values_mut();
188 Definition::Adt(hir::Adt::Enum(enum_)) => {
190 it.retain(|reference| {
194 .map_or(false, |name_ref| is_enum_lit_name_ref(sema, enum_, name_ref))
197 usages.references.retain(|_, it| !it.is_empty());
199 Definition::Adt(_) | Definition::Variant(_) => {
201 it.retain(|reference| reference.name.as_name_ref().map_or(false, is_lit_name_ref))
203 usages.references.retain(|_, it| !it.is_empty());
209 /// Returns `Some` if the cursor is at a position for an item to search for all its constructor/literal usages
210 fn name_for_constructor_search(syntax: &SyntaxNode, position: FilePosition) -> Option<ast::Name> {
211 let token = syntax.token_at_offset(position.offset).right_biased()?;
212 let token_parent = token.parent()?;
213 let kind = token.kind();
215 ast::Struct::cast(token_parent)
216 .filter(|struct_| struct_.field_list().is_none())
217 .and_then(|struct_| struct_.name())
218 } else if kind == T!['{'] {
221 ast::RecordFieldList(rfl) => match_ast! {
222 match (rfl.syntax().parent()?) {
223 ast::Variant(it) => it.name(),
224 ast::Struct(it) => it.name(),
225 ast::Union(it) => it.name(),
229 ast::VariantList(vl) => ast::Enum::cast(vl.syntax().parent()?)?.name(),
233 } else if kind == T!['('] {
234 let tfl = ast::TupleFieldList::cast(token_parent)?;
236 match (tfl.syntax().parent()?) {
237 ast::Variant(it) => it.name(),
238 ast::Struct(it) => it.name(),
247 fn is_enum_lit_name_ref(
248 sema: &Semantics<'_, RootDatabase>,
250 name_ref: &ast::NameRef,
252 let path_is_variant_of_enum = |path: ast::Path| {
254 sema.resolve_path(&path),
255 Some(PathResolution::Def(hir::ModuleDef::Variant(variant)))
256 if variant.parent_enum(sema.db) == enum_
262 .find_map(|ancestor| {
265 ast::PathExpr(path_expr) => path_expr.path().map(path_is_variant_of_enum),
266 ast::RecordExpr(record_expr) => record_expr.path().map(path_is_variant_of_enum),
274 fn path_ends_with(path: Option<ast::Path>, name_ref: &ast::NameRef) -> bool {
275 path.and_then(|path| path.segment())
276 .and_then(|segment| segment.name_ref())
277 .map_or(false, |segment| segment == *name_ref)
280 fn is_lit_name_ref(name_ref: &ast::NameRef) -> bool {
281 name_ref.syntax().ancestors().find_map(|ancestor| {
284 ast::PathExpr(path_expr) => Some(path_ends_with(path_expr.path(), name_ref)),
285 ast::RecordExpr(record_expr) => Some(path_ends_with(record_expr.path(), name_ref)),
294 use expect_test::{expect, Expect};
295 use ide_db::{base_db::FileId, search::ReferenceCategory};
298 use crate::{fixture, SearchScope};
301 fn test_struct_literal_after_space() {
312 f = Foo {a: Foo::f()};
316 Foo Struct FileId(0) 0..26 7..10
324 fn test_struct_literal_before_space() {
334 Foo Struct FileId(0) 0..13 7..10
343 fn test_struct_literal_with_generic_type() {
353 Foo Struct FileId(0) 0..16 7..10
361 fn test_struct_literal_for_tuple() {
372 Foo Struct FileId(0) 0..16 7..10
380 fn test_struct_literal_for_union() {
393 Foo Union FileId(0) 0..24 6..9
401 fn test_enum_after_space() {
417 Foo Enum FileId(0) 0..37 5..8
427 fn test_variant_record_after_space() {
437 f = Foo::A { n: 92 };
441 A Variant FileId(0) 15..27 15..16
448 fn test_variant_tuple_before_paren() {
462 A Variant FileId(0) 15..21 15..16
470 fn test_enum_before_space() {
483 Foo Enum FileId(0) 0..26 5..8
492 fn test_enum_with_generic_type() {
505 Foo Enum FileId(0) 0..32 5..8
513 fn test_enum_for_tuple() {
526 Foo Enum FileId(0) 0..33 5..8
534 fn test_find_all_refs_for_local() {
549 i Local FileId(0) 20..25 24..25 Write
551 FileId(0) 50..51 Write
552 FileId(0) 54..55 Read
553 FileId(0) 76..77 Write
554 FileId(0) 94..95 Write
560 fn search_filters_by_range() {
573 spam Local FileId(0) 19..23 19..23
575 FileId(0) 34..38 Read
576 FileId(0) 41..45 Read
582 fn test_find_all_refs_for_param_inside() {
585 fn foo(i : u32) -> u32 { i$0 }
588 i ValueParam FileId(0) 7..8 7..8
590 FileId(0) 25..26 Read
596 fn test_find_all_refs_for_fn_param() {
599 fn foo(i$0 : u32) -> u32 { i }
602 i ValueParam FileId(0) 7..8 7..8
604 FileId(0) 25..26 Read
610 fn test_find_all_refs_field_name() {
623 spam Field FileId(0) 17..30 21..25
625 FileId(0) 67..71 Read
631 fn test_find_all_refs_impl_item_name() {
640 f Function FileId(0) 27..43 30..31
648 fn test_find_all_refs_enum_var_name() {
658 B Variant FileId(0) 22..23 22..23
666 fn test_find_all_refs_enum_var_field() {
676 field Field FileId(0) 26..35 26..31
684 fn test_find_all_refs_two_modules() {
692 let i = foo::Foo { n: 5 };
703 let i = bar::Bar { n: 5 };
714 let i = foo::Foo$0 { n: 5 };
718 Foo Struct FileId(1) 17..51 28..31
727 fn test_find_all_refs_decl_module() {
736 let i = Foo { n: 5 };
745 foo Module FileId(0) 0..8 4..7
747 FileId(0) 14..17 Import
753 fn test_find_all_refs_decl_module_on_self() {
763 foo Module FileId(0) 0..8 4..7
765 FileId(1) 4..8 Import
771 fn test_find_all_refs_decl_module_on_self_crate_root() {
778 Module FileId(0) 0..10
780 FileId(0) 4..8 Import
786 fn test_find_all_refs_super_mod_vis() {
797 let i = Foo { n: 5 };
801 pub(super) struct Foo$0 {
806 Foo Struct FileId(2) 0..41 18..21
808 FileId(1) 20..23 Import
815 fn test_find_all_refs_with_scope() {
824 fn f() { super::quux(); }
827 fn f() { super::quux(); }
834 quux Function FileId(0) 19..35 26..30
843 Some(SearchScope::single_file(FileId(2))),
845 quux Function FileId(0) 19..35 26..30
853 fn test_find_all_refs_macro_def() {
857 macro_rules! m1$0 { () => (()) }
865 m1 Macro FileId(0) 0..46 29..31
874 fn test_basic_highlight_read_write() {
883 i Local FileId(0) 19..24 23..24 Write
885 FileId(0) 34..35 Write
886 FileId(0) 38..39 Read
892 fn test_basic_highlight_field_read_write() {
905 f Field FileId(0) 15..21 15..16
907 FileId(0) 55..56 Read
908 FileId(0) 68..69 Write
914 fn test_basic_highlight_decl_no_write() {
923 i Local FileId(0) 19..20 19..20
925 FileId(0) 26..27 Write
931 fn test_find_struct_function_refs_outside_module() {
938 pub fn new$0() -> Foo { Foo }
943 let _f = foo::Foo::new();
947 new Function FileId(0) 54..81 61..64
955 fn test_find_all_refs_nested_module() {
969 f Function FileId(0) 22..31 25..26
971 FileId(1) 11..12 Import
978 fn test_find_all_refs_struct_pat() {
992 field Field FileId(0) 15..24 15..20
994 FileId(0) 68..73 Read
1000 fn test_find_all_refs_enum_var_pat() {
1011 En::Variant { field } => {}
1016 field Field FileId(0) 32..41 32..37
1018 FileId(0) 102..107 Read
1024 fn test_find_all_refs_enum_var_privacy() {
1036 m::En::Variant { field: 0 }
1040 field Field FileId(0) 56..65 56..61
1042 FileId(0) 125..130 Read
1048 fn test_find_self_refs() {
1051 struct Foo { bar: i32 }
1065 self SelfParam FileId(0) 47..51 47..51
1067 FileId(0) 71..75 Read
1068 FileId(0) 152..156 Read
1074 fn test_find_self_refs_decl() {
1077 struct Foo { bar: i32 }
1086 self SelfParam FileId(0) 47..51 47..51
1088 FileId(0) 63..67 Read
1093 fn check(ra_fixture: &str, expect: Expect) {
1094 check_with_scope(ra_fixture, None, expect)
1097 fn check_with_scope(ra_fixture: &str, search_scope: Option<SearchScope>, expect: Expect) {
1098 let (analysis, pos) = fixture::position(ra_fixture);
1099 let refs = analysis.find_all_refs(pos, search_scope).unwrap().unwrap();
1101 let mut actual = String::new();
1105 if let Some(decl) = refs.declaration {
1106 format_to!(actual, "{}", decl.nav.debug_render());
1108 format_to!(actual, " {:?}", ReferenceCategory::Write)
1113 for (file_id, references) in &refs.references {
1114 for (range, access) in references {
1115 format_to!(actual, "{:?} {:?}", file_id, range);
1116 if let Some(access) = access {
1117 format_to!(actual, " {:?}", access);
1123 if refs.references.is_empty() {
1124 actual += "(no references)\n";
1127 expect.assert_eq(actual.trim_start())
1131 fn test_find_lifetimes_function() {
1135 impl<'a> Foo<'a> for &'a () {}
1136 fn foo<'a, 'b: 'a>(x: &'a$0 ()) -> &'a () where &'a (): Foo<'a> {
1137 fn bar<'a>(_: &'a ()) {}
1142 'a LifetimeParam FileId(0) 55..57 55..57
1154 fn test_find_lifetimes_type_alias() {
1157 type Foo<'a, T> where T: 'a$0 = &'a T;
1160 'a LifetimeParam FileId(0) 9..11 9..11
1169 fn test_find_lifetimes_trait_impl() {
1175 impl<'a> Foo<'a> for &'a () {
1176 fn foo() -> &'a$0 () {
1182 'a LifetimeParam FileId(0) 47..49 47..49
1192 fn test_map_range_to_original() {
1195 macro_rules! foo {($i:ident) => {$i} }
1202 a Local FileId(0) 59..60 59..60
1204 FileId(0) 80..81 Read
1210 fn test_map_range_to_original_ref() {
1213 macro_rules! foo {($i:ident) => {$i} }
1220 a Local FileId(0) 59..60 59..60
1222 FileId(0) 80..81 Read
1228 fn test_find_labels() {
1231 fn foo<'a>() -> &'a () {
1241 'a Label FileId(0) 29..32 29..31
1250 fn test_find_const_param() {
1253 fn foo<const FOO$0: usize>() -> usize {
1258 FOO ConstParam FileId(0) 7..23 13..16
1269 trait Foo$0 where Self: {}
1274 Foo Trait FileId(0) 0..24 6..9
1282 fn test_trait_self() {
1285 trait Foo where Self$0 {
1292 Self TypeParam FileId(0) 6..9 6..9
1306 impl Foo where Self: {
1311 Foo Struct FileId(0) 0..11 7..10
1322 impl Foo where Self: {
1327 impl Impl FileId(0) 13..57 18..21
1336 fn test_self_variant_with_payload() {
1344 Self::Bar$0() => (),
1351 Bar Variant FileId(0) 11..16 11..14
1359 fn test_attr_differs_from_fn_with_same_name() {
1368 test Function FileId(0) 0..33 11..15
1376 fn test_const_in_pattern() {
1379 const A$0: i32 = 42;
1390 A Const FileId(0) 0..18 6..7
1401 fn test_primitives() {
1404 fn foo(_: bool) -> bo$0ol { true }
1414 fn test_transitive() {
1417 //- /level3.rs new_source_root:local crate:level3
1419 //- /level2.rs new_source_root:local crate:level2 deps:level3
1420 pub use level3::Foo;
1421 //- /level1.rs new_source_root:local crate:level1 deps:level2
1422 pub use level2::Foo;
1423 //- /level0.rs new_source_root:local crate:level0 deps:level1
1424 pub use level1::Foo;
1427 Foo Struct FileId(0) 0..15 11..14
1429 FileId(1) 16..19 Import
1430 FileId(2) 16..19 Import
1431 FileId(3) 16..19 Import
1437 fn test_decl_macro_references() {
1440 //- /lib.rs crate:lib
1448 macro_rules! foo$0 {
1449 () => {struct Foo;};
1453 //- /other.rs crate:other deps:lib new_source_root:local
1457 foo Macro FileId(1) 0..61 29..32
1459 FileId(0) 46..49 Import
1467 fn macro_doesnt_reference_attribute_on_call() {
1474 #[proc_macro_test::attr_noop]
1479 m Macro FileId(0) 0..32 13..14
1508 func Function FileId(0) 137..146 140..144
1513 func Function FileId(0) 137..146 140..144
1521 fn attr_expanded() {
1524 //- proc_macros: identity
1525 #[proc_macros::identity]
1531 func Function FileId(0) 25..50 28..32
1539 fn attr_assoc_item() {
1542 //- proc_macros: identity
1545 #[proc_macros::identity]
1552 func Function FileId(0) 48..87 51..55
1559 // FIXME: import is classified as function
1564 //- proc_macros: identity
1565 use proc_macros::identity;
1567 #[proc_macros::$0identity]
1571 identity Attribute FileId(1) 1..107 32..40
1578 #![crate_type="proc-macro"]
1579 #[proc_macro_attribute]
1583 func Attribute FileId(0) 28..64 55..59
1590 // FIXME: import is classified as function
1595 //- proc_macros: mirror
1596 use proc_macros::mirror;
1601 mirror Macro FileId(1) 1..77 22..28
1612 //- proc_macros: derive_identity
1613 //- minicore: derive
1614 use proc_macros::DeriveIdentity;
1616 #[derive(proc_macros::DeriveIdentity$0)]
1620 derive_identity Derive FileId(2) 1..107 45..60
1622 FileId(0) 17..31 Import
1628 #![crate_type="proc-macro"]
1629 #[proc_macro_derive(Derive, attributes(x))]
1630 pub fn deri$0ve(_stream: TokenStream) -> TokenStream {}
1633 derive Derive FileId(0) 28..125 79..85