Skip to main content

ide_db/
search.rs

1//! Implementation of find-usages functionality.
2//!
3//! It is based on the standard ide trick: first, we run a fast text search to
4//! get a super-set of matches. Then, we confirm each match using precise
5//! name resolution.
6
7use std::mem;
8use std::{cell::LazyCell, cmp::Reverse};
9
10use base_db::{SourceDatabase, all_crates};
11use either::Either;
12use hir::{
13    Adt, AsAssocItem, DefWithBody, EditionedFileId, ExpressionStoreOwner, FileRange,
14    FileRangeWrapper, HasContainer, HasSource, InFile, InFileWrapper, InRealFile, InlineAsmOperand,
15    ItemContainer, ModuleSource, PathResolution, Semantics, Visibility,
16};
17use memchr::memmem::Finder;
18use parser::SyntaxKind;
19use rustc_hash::{FxHashMap, FxHashSet};
20use salsa::Database;
21use syntax::{
22    AstNode, AstToken, SmolStr, SyntaxElement, SyntaxNode, TextRange, TextSize, ToSmolStr,
23    ast::{self, HasName, Rename},
24    match_ast,
25};
26use triomphe::Arc;
27
28use crate::{
29    RootDatabase,
30    defs::{Definition, NameClass, NameRefClass},
31    traits::{as_trait_assoc_def, convert_to_def_in_trait},
32};
33
34#[derive(Debug, Default, Clone)]
35pub struct UsageSearchResult {
36    pub references: FxHashMap<EditionedFileId, Vec<FileReference>>,
37}
38
39impl UsageSearchResult {
40    pub fn is_empty(&self) -> bool {
41        self.references.is_empty()
42    }
43
44    pub fn len(&self) -> usize {
45        self.references.len()
46    }
47
48    pub fn iter(&self) -> impl Iterator<Item = (EditionedFileId, &[FileReference])> + '_ {
49        self.references.iter().map(|(&file_id, refs)| (file_id, &**refs))
50    }
51
52    pub fn file_ranges(&self) -> impl Iterator<Item = FileRange> + '_ {
53        self.references.iter().flat_map(|(&file_id, refs)| {
54            refs.iter().map(move |&FileReference { range, .. }| FileRange { file_id, range })
55        })
56    }
57}
58
59impl IntoIterator for UsageSearchResult {
60    type Item = (EditionedFileId, Vec<FileReference>);
61    type IntoIter = <FxHashMap<EditionedFileId, Vec<FileReference>> as IntoIterator>::IntoIter;
62
63    fn into_iter(self) -> Self::IntoIter {
64        self.references.into_iter()
65    }
66}
67
68#[derive(Debug, Clone)]
69pub struct FileReference {
70    /// The range of the reference in the original file
71    pub range: TextRange,
72    /// The node of the reference in the (macro-)file
73    pub name: FileReferenceNode,
74    pub category: ReferenceCategory,
75}
76
77#[derive(Debug, Clone)]
78pub enum FileReferenceNode {
79    Name(ast::Name),
80    NameRef(ast::NameRef),
81    Lifetime(ast::Lifetime),
82    FormatStringEntry(ast::String, TextRange),
83}
84
85impl FileReferenceNode {
86    pub fn text_range(&self) -> TextRange {
87        match self {
88            FileReferenceNode::Name(it) => it.syntax().text_range(),
89            FileReferenceNode::NameRef(it) => it.syntax().text_range(),
90            FileReferenceNode::Lifetime(it) => it.syntax().text_range(),
91            FileReferenceNode::FormatStringEntry(_, range) => *range,
92        }
93    }
94    pub fn syntax(&self) -> SyntaxElement {
95        match self {
96            FileReferenceNode::Name(it) => it.syntax().clone().into(),
97            FileReferenceNode::NameRef(it) => it.syntax().clone().into(),
98            FileReferenceNode::Lifetime(it) => it.syntax().clone().into(),
99            FileReferenceNode::FormatStringEntry(it, _) => it.syntax().clone().into(),
100        }
101    }
102    pub fn into_name_like(self) -> Option<ast::NameLike> {
103        match self {
104            FileReferenceNode::Name(it) => Some(ast::NameLike::Name(it)),
105            FileReferenceNode::NameRef(it) => Some(ast::NameLike::NameRef(it)),
106            FileReferenceNode::Lifetime(it) => Some(ast::NameLike::Lifetime(it)),
107            FileReferenceNode::FormatStringEntry(_, _) => None,
108        }
109    }
110    pub fn as_name_ref(&self) -> Option<&ast::NameRef> {
111        match self {
112            FileReferenceNode::NameRef(name_ref) => Some(name_ref),
113            _ => None,
114        }
115    }
116    pub fn as_lifetime(&self) -> Option<&ast::Lifetime> {
117        match self {
118            FileReferenceNode::Lifetime(lifetime) => Some(lifetime),
119            _ => None,
120        }
121    }
122    pub fn text(&self) -> &str {
123        match self {
124            FileReferenceNode::NameRef(name_ref) => name_ref.text(),
125            FileReferenceNode::Name(name) => name.text(),
126            FileReferenceNode::Lifetime(lifetime) => lifetime.text(),
127            FileReferenceNode::FormatStringEntry(it, range) => {
128                &it.text()[*range - it.syntax().text_range().start()]
129            }
130        }
131    }
132}
133
134bitflags::bitflags! {
135    #[derive(Copy, Clone, Default, PartialEq, Eq, Hash, Debug)]
136    pub struct ReferenceCategory: u8 {
137        // FIXME: Add this variant and delete the `retain_adt_literal_usages` function.
138        // const CREATE = 1 << 0;
139        const WRITE = 1 << 0;
140        const READ = 1 << 1;
141        const IMPORT = 1 << 2;
142        const TEST = 1 << 3;
143    }
144}
145
146/// Generally, `search_scope` returns files that might contain references for the element.
147/// For `pub(crate)` things it's a crate, for `pub` things it's a crate and dependant crates.
148/// In some cases, the location of the references is known to within a `TextRange`,
149/// e.g. for things like local variables.
150#[derive(Clone, Debug)]
151pub struct SearchScope {
152    entries: FxHashMap<EditionedFileId, Option<TextRange>>,
153}
154
155impl SearchScope {
156    fn new(entries: FxHashMap<EditionedFileId, Option<TextRange>>) -> SearchScope {
157        SearchScope { entries }
158    }
159
160    /// Build a search scope spanning the entire crate graph of files.
161    fn crate_graph(db: &RootDatabase) -> SearchScope {
162        let mut entries = FxHashMap::default();
163
164        let all_crates = all_crates(db);
165        for &krate in all_crates.iter() {
166            let crate_data = krate.data(db);
167            let source_root = db.file_source_root(crate_data.root_file_id).source_root_id(db);
168            let source_root = db.source_root(source_root).source_root(db);
169            entries.extend(
170                source_root
171                    .iter()
172                    .map(|id| (EditionedFileId::new(db, id, crate_data.edition), None)),
173            );
174        }
175        SearchScope { entries }
176    }
177
178    /// Build a search scope spanning all the reverse dependencies of the given crate.
179    fn reverse_dependencies(db: &RootDatabase, of: hir::Crate) -> SearchScope {
180        let mut entries = FxHashMap::default();
181        for rev_dep in of.transitive_reverse_dependencies(db) {
182            let root_file = rev_dep.root_file(db);
183
184            let source_root = db.file_source_root(root_file).source_root_id(db);
185            let source_root = db.source_root(source_root).source_root(db);
186            entries.extend(
187                source_root
188                    .iter()
189                    .map(|id| (EditionedFileId::new(db, id, rev_dep.edition(db)), None)),
190            );
191        }
192        SearchScope { entries }
193    }
194
195    /// Build a search scope spanning the given crate.
196    fn krate(db: &RootDatabase, of: hir::Crate) -> SearchScope {
197        let root_file = of.root_file(db);
198
199        let source_root_id = db.file_source_root(root_file).source_root_id(db);
200        let source_root = db.source_root(source_root_id).source_root(db);
201        SearchScope {
202            entries: source_root
203                .iter()
204                .map(|id| (EditionedFileId::new(db, id, of.edition(db)), None))
205                .collect(),
206        }
207    }
208
209    /// Build a search scope spanning the given module and all its submodules.
210    pub fn module_and_children(db: &RootDatabase, module: hir::Module) -> SearchScope {
211        let mut entries = FxHashMap::default();
212
213        let (file_id, range) = {
214            let InFile { file_id, value } = module.definition_source_range(db);
215            if let Some(InRealFile { file_id, value: call_source }) = file_id.original_call_node(db)
216            {
217                (file_id, Some(call_source.text_range()))
218            } else {
219                (file_id.original_file(db), Some(value))
220            }
221        };
222        entries.entry(file_id).or_insert(range);
223
224        let mut to_visit: Vec<_> = module.children(db).collect();
225        while let Some(module) = to_visit.pop() {
226            if let Some(file_id) = module.as_source_file_id(db) {
227                entries.insert(file_id, None);
228            }
229            to_visit.extend(module.children(db));
230        }
231        SearchScope { entries }
232    }
233
234    /// Build an empty search scope.
235    pub fn empty() -> SearchScope {
236        SearchScope::new(FxHashMap::default())
237    }
238
239    /// Build a empty search scope spanning the given file.
240    pub fn single_file(file: EditionedFileId) -> SearchScope {
241        SearchScope::new(std::iter::once((file, None)).collect())
242    }
243
244    /// Build a empty search scope spanning the text range of the given file.
245    pub fn file_range(range: FileRange) -> SearchScope {
246        SearchScope::new(std::iter::once((range.file_id, Some(range.range))).collect())
247    }
248
249    /// Build a empty search scope spanning the given files.
250    pub fn files(files: &[EditionedFileId]) -> SearchScope {
251        SearchScope::new(files.iter().map(|f| (*f, None)).collect())
252    }
253
254    pub fn intersection(&self, other: &SearchScope) -> SearchScope {
255        let (mut small, mut large) = (&self.entries, &other.entries);
256        if small.len() > large.len() {
257            mem::swap(&mut small, &mut large)
258        }
259
260        let intersect_ranges =
261            |r1: Option<TextRange>, r2: Option<TextRange>| -> Option<Option<TextRange>> {
262                match (r1, r2) {
263                    (None, r) | (r, None) => Some(r),
264                    (Some(r1), Some(r2)) => r1.intersect(r2).map(Some),
265                }
266            };
267        let res = small
268            .iter()
269            .filter_map(|(&file_id, &r1)| {
270                let &r2 = large.get(&file_id)?;
271                let r = intersect_ranges(r1, r2)?;
272                Some((file_id, r))
273            })
274            .collect();
275
276        SearchScope::new(res)
277    }
278}
279
280impl IntoIterator for SearchScope {
281    type Item = (EditionedFileId, Option<TextRange>);
282    type IntoIter = std::collections::hash_map::IntoIter<EditionedFileId, Option<TextRange>>;
283
284    fn into_iter(self) -> Self::IntoIter {
285        self.entries.into_iter()
286    }
287}
288
289impl<'db> Definition<'db> {
290    fn search_scope(&self, db: &RootDatabase) -> SearchScope {
291        let _p = tracing::info_span!("search_scope").entered();
292
293        if let Definition::BuiltinType(_) = self {
294            return SearchScope::crate_graph(db);
295        }
296
297        // def is crate root
298        if let &Definition::Module(module) = self
299            && module.is_crate_root(db)
300        {
301            return SearchScope::reverse_dependencies(db, module.krate(db));
302        }
303
304        let module = match self.module(db) {
305            Some(it) => it,
306            None => return SearchScope::empty(),
307        };
308        let InFile { file_id, value: module_source } = module.definition_source(db);
309        let file_id = file_id.original_file(db);
310
311        if let Definition::Local(var) = self {
312            let def = match var.parent(db) {
313                ExpressionStoreOwner::Body(def) => match def {
314                    DefWithBody::Function(f) => f.source(db).map(|src| src.syntax().cloned()),
315                    DefWithBody::Const(c) => c.source(db).map(|src| src.syntax().cloned()),
316                    DefWithBody::Static(s) => s.source(db).map(|src| src.syntax().cloned()),
317                    DefWithBody::EnumVariant(v) => v.source(db).map(|src| src.syntax().cloned()),
318                },
319                ExpressionStoreOwner::Signature(def) => match def {
320                    hir::GenericDef::Function(it) => it.source(db).map(|src| src.syntax().cloned()),
321                    hir::GenericDef::Adt(it) => it.source(db).map(|src| src.syntax().cloned()),
322                    hir::GenericDef::Trait(it) => it.source(db).map(|src| src.syntax().cloned()),
323                    hir::GenericDef::TypeAlias(it) => {
324                        it.source(db).map(|src| src.syntax().cloned())
325                    }
326                    hir::GenericDef::Impl(it) => it.source(db).map(|src| src.syntax().cloned()),
327                    hir::GenericDef::Const(it) => it.source(db).map(|src| src.syntax().cloned()),
328                    hir::GenericDef::Static(it) => it.source(db).map(|src| src.syntax().cloned()),
329                },
330                ExpressionStoreOwner::VariantFields(it) => {
331                    it.source(db).map(|src| src.syntax().cloned())
332                }
333            };
334            return match def {
335                Some(def) => SearchScope::file_range(
336                    def.as_ref().original_file_range_with_macro_call_input(db),
337                ),
338                None => SearchScope::single_file(file_id),
339            };
340        }
341
342        if let Definition::InlineAsmOperand(op) = self {
343            let def = match op.parent(db) {
344                ExpressionStoreOwner::Body(def) => match def {
345                    DefWithBody::Function(f) => f.source(db).map(|src| src.syntax().cloned()),
346                    DefWithBody::Const(c) => c.source(db).map(|src| src.syntax().cloned()),
347                    DefWithBody::Static(s) => s.source(db).map(|src| src.syntax().cloned()),
348                    DefWithBody::EnumVariant(v) => v.source(db).map(|src| src.syntax().cloned()),
349                },
350                ExpressionStoreOwner::Signature(def) => match def {
351                    hir::GenericDef::Function(it) => it.source(db).map(|src| src.syntax().cloned()),
352                    hir::GenericDef::Adt(it) => it.source(db).map(|src| src.syntax().cloned()),
353                    hir::GenericDef::Trait(it) => it.source(db).map(|src| src.syntax().cloned()),
354                    hir::GenericDef::TypeAlias(it) => {
355                        it.source(db).map(|src| src.syntax().cloned())
356                    }
357                    hir::GenericDef::Impl(it) => it.source(db).map(|src| src.syntax().cloned()),
358                    hir::GenericDef::Const(it) => it.source(db).map(|src| src.syntax().cloned()),
359                    hir::GenericDef::Static(it) => it.source(db).map(|src| src.syntax().cloned()),
360                },
361                ExpressionStoreOwner::VariantFields(it) => {
362                    it.source(db).map(|src| src.syntax().cloned())
363                }
364            };
365            return match def {
366                Some(def) => SearchScope::file_range(
367                    def.as_ref().original_file_range_with_macro_call_input(db),
368                ),
369                None => SearchScope::single_file(file_id),
370            };
371        }
372
373        if let Definition::SelfType(impl_) = self {
374            return match impl_.source(db).map(|src| src.syntax().cloned()) {
375                Some(def) => SearchScope::file_range(
376                    def.as_ref().original_file_range_with_macro_call_input(db),
377                ),
378                None => SearchScope::single_file(file_id),
379            };
380        }
381
382        if let Definition::GenericParam(hir::GenericParam::LifetimeParam(param)) = self {
383            let def = match param.parent(db) {
384                hir::GenericDef::Function(it) => it.source(db).map(|src| src.syntax().cloned()),
385                hir::GenericDef::Adt(it) => it.source(db).map(|src| src.syntax().cloned()),
386                hir::GenericDef::Trait(it) => it.source(db).map(|src| src.syntax().cloned()),
387                hir::GenericDef::TypeAlias(it) => it.source(db).map(|src| src.syntax().cloned()),
388                hir::GenericDef::Impl(it) => it.source(db).map(|src| src.syntax().cloned()),
389                hir::GenericDef::Const(it) => it.source(db).map(|src| src.syntax().cloned()),
390                hir::GenericDef::Static(it) => it.source(db).map(|src| src.syntax().cloned()),
391            };
392            return match def {
393                Some(def) => SearchScope::file_range(
394                    def.as_ref().original_file_range_with_macro_call_input(db),
395                ),
396                None => SearchScope::single_file(file_id),
397            };
398        }
399
400        if let Definition::DeriveHelper(_) = self {
401            return SearchScope::reverse_dependencies(db, module.krate(db));
402        }
403
404        if let Some(vis) = self.visibility(db) {
405            return match vis {
406                Visibility::Module(module, _) => {
407                    SearchScope::module_and_children(db, module.into())
408                }
409                Visibility::PubCrate(krate) => SearchScope::krate(db, krate.into()),
410                Visibility::Public => SearchScope::reverse_dependencies(db, module.krate(db)),
411            };
412        }
413
414        let range = match module_source {
415            ModuleSource::Module(m) => Some(m.syntax().text_range()),
416            ModuleSource::BlockExpr(b) => Some(b.syntax().text_range()),
417            ModuleSource::SourceFile(_) => None,
418        };
419        match range {
420            Some(range) => SearchScope::file_range(FileRange { file_id, range }),
421            None => SearchScope::single_file(file_id),
422        }
423    }
424
425    pub fn usages<'a>(self, sema: &'a Semantics<'db, RootDatabase>) -> FindUsages<'a, 'db> {
426        FindUsages {
427            def: self,
428            rename: None,
429            assoc_item_container: self.as_assoc_item(sema.db).map(|a| a.container(sema.db)),
430            sema,
431            scope: None,
432            include_self_kw_refs: None,
433            search_self_mod: false,
434            included_categories: ReferenceCategory::all(),
435            exclude_library_files: false,
436        }
437    }
438}
439
440#[derive(Clone)]
441pub struct FindUsages<'a, 'db> {
442    def: Definition<'db>,
443    rename: Option<&'a Rename>,
444    sema: &'a Semantics<'db, RootDatabase>,
445    scope: Option<&'a SearchScope>,
446    /// The container of our definition should it be an assoc item
447    assoc_item_container: Option<hir::AssocItemContainer>,
448    /// whether to search for the `Self` type of the definition
449    include_self_kw_refs: Option<hir::Type<'a>>,
450    /// whether to search for the `self` module
451    search_self_mod: bool,
452    /// categories to include while collecting usages
453    included_categories: ReferenceCategory,
454    /// whether to skip files from library source roots
455    exclude_library_files: bool,
456}
457
458impl<'a, 'db> FindUsages<'a, 'db> {
459    /// Enable searching for `Self` when the definition is a type or `self` for modules.
460    pub fn include_self_refs(mut self) -> Self {
461        self.include_self_kw_refs = def_to_ty(self.sema, &self.def);
462        self.search_self_mod = true;
463        self
464    }
465
466    /// Limit the search to a given [`SearchScope`].
467    pub fn in_scope(self, scope: &'a SearchScope) -> Self {
468        self.set_scope(Some(scope))
469    }
470
471    /// Limit the search to a given [`SearchScope`].
472    pub fn set_scope(mut self, scope: Option<&'a SearchScope>) -> Self {
473        assert!(self.scope.is_none());
474        self.scope = scope;
475        self
476    }
477
478    // FIXME: This is just a temporary fix for not handling import aliases like
479    // `use Foo as Bar`. We need to support them in a proper way.
480    // See issue #14079
481    pub fn with_rename(mut self, rename: Option<&'a Rename>) -> Self {
482        self.rename = rename;
483        self
484    }
485
486    pub fn set_included_categories(mut self, categories: ReferenceCategory) -> Self {
487        self.included_categories = categories;
488        self
489    }
490
491    pub fn set_exclude_library_files(mut self, exclude_library_files: bool) -> Self {
492        self.exclude_library_files = exclude_library_files;
493        self
494    }
495
496    pub fn at_least_one(&self) -> bool {
497        let mut found = false;
498        self.search(&mut |_, _| {
499            found = true;
500            true
501        });
502        found
503    }
504
505    pub fn all(self) -> UsageSearchResult {
506        let mut res = UsageSearchResult::default();
507        self.search(&mut |file_id, reference| {
508            res.references.entry(file_id).or_default().push(reference);
509            false
510        });
511        res
512    }
513
514    fn scope_files<'b>(
515        db: &'b RootDatabase,
516        scope: &'b SearchScope,
517        exclude_library_files: bool,
518    ) -> impl Iterator<Item = (Arc<str>, EditionedFileId, TextRange)> + 'b {
519        scope
520            .entries
521            .iter()
522            .filter(move |(file_id, _)| {
523                !exclude_library_files || !is_library_file(db, file_id.file_id(db))
524            })
525            .map(|(&file_id, &search_range)| {
526                let text = db.file_text(file_id.file_id(db)).text(db);
527                let search_range =
528                    search_range.unwrap_or_else(|| TextRange::up_to(TextSize::of(&**text)));
529
530                (text.clone(), file_id, search_range)
531            })
532    }
533
534    fn match_indices<'b>(
535        text: &'b str,
536        finder: &'b Finder<'b>,
537        search_range: TextRange,
538    ) -> impl Iterator<Item = TextSize> + 'b {
539        finder.find_iter(text.as_bytes()).filter_map(move |idx| {
540            let offset: TextSize = idx.try_into().unwrap();
541            if !search_range.contains_inclusive(offset) {
542                return None;
543            }
544            // If this is not a word boundary, that means this is only part of an identifier,
545            // so it can't be what we're looking for.
546            // This speeds up short identifiers significantly.
547            if text[..idx]
548                .chars()
549                .next_back()
550                .is_some_and(|ch| matches!(ch, 'A'..='Z' | 'a'..='z' | '_'))
551                || text[idx + finder.needle().len()..]
552                    .chars()
553                    .next()
554                    .is_some_and(|ch| matches!(ch, 'A'..='Z' | 'a'..='z' | '_' | '0'..='9'))
555            {
556                return None;
557            }
558            Some(offset)
559        })
560    }
561
562    fn find_nodes<'b>(
563        sema: &'b Semantics<'_, RootDatabase>,
564        name: &str,
565        file_id: EditionedFileId,
566        node: &syntax::SyntaxNode,
567        offset: TextSize,
568    ) -> impl Iterator<Item = SyntaxNode> + 'b {
569        node.token_at_offset(offset)
570            .find(|it| {
571                // `name` is stripped of raw ident prefix. See the comment on name retrieval below.
572                it.text().trim_start_matches('\'').trim_start_matches("r#") == name
573            })
574            .into_iter()
575            .flat_map(move |token| {
576                if sema.is_inside_macro_call(InFile::new(file_id.into(), &token)) {
577                    sema.descend_into_macros_exact(token)
578                } else {
579                    <_>::from([token])
580                }
581                .into_iter()
582                .filter_map(|it| it.parent())
583            })
584    }
585
586    /// Performs a special fast search for associated functions. This is mainly intended
587    /// to speed up `new()` which can take a long time.
588    ///
589    /// The trick is instead of searching for `func_name` search for `TypeThatContainsContainerName::func_name`.
590    /// We cannot search exactly that (not even in tokens), because `ContainerName` may be aliased.
591    /// Instead, we perform a textual search for `ContainerName`. Then, we look for all cases where
592    /// `ContainerName` may be aliased (that includes `use ContainerName as Xyz` and
593    /// `type Xyz = ContainerName`). We collect a list of all possible aliases of `ContainerName`.
594    /// The list can have false positives (because there may be multiple types named `ContainerName`),
595    /// but it cannot have false negatives. Then, we look for `TypeThatContainsContainerNameOrAnyAlias::func_name`.
596    /// Those that will be found are of high chance to be actual hits (of course, we will need to verify
597    /// that).
598    ///
599    /// Returns true if completed the search.
600    // FIXME: Extend this to other cases, such as associated types/consts/enum variants (note those can be `use`d).
601    fn short_associated_function_fast_search(
602        &self,
603        sink: &mut dyn FnMut(EditionedFileId, FileReference) -> bool,
604        search_scope: &SearchScope,
605        name: &str,
606    ) -> bool {
607        if self.scope.is_some() {
608            return false;
609        }
610
611        let _p = tracing::info_span!("short_associated_function_fast_search").entered();
612
613        let container = (|| {
614            let Definition::Function(function) = self.def else {
615                return None;
616            };
617            if function.has_self_param(self.sema.db) {
618                return None;
619            }
620            match function.container(self.sema.db) {
621                // Only freestanding `impl`s qualify; methods from trait
622                // can be called from within subtraits and bounds.
623                ItemContainer::Impl(impl_) => {
624                    let has_trait = impl_.trait_(self.sema.db).is_some();
625                    if has_trait {
626                        return None;
627                    }
628                    let adt = impl_.self_ty(self.sema.db).as_adt()?;
629                    Some(adt)
630                }
631                _ => None,
632            }
633        })();
634        let Some(container) = container else {
635            return false;
636        };
637
638        fn has_any_name(node: &SyntaxNode, mut predicate: impl FnMut(&str) -> bool) -> bool {
639            node.descendants().any(|node| {
640                match_ast! {
641                    match node {
642                        ast::Name(it) => predicate(it.text().trim_start_matches("r#")),
643                        ast::NameRef(it) => predicate(it.text().trim_start_matches("r#")),
644                        _ => false
645                    }
646                }
647            })
648        }
649
650        // This is a fixpoint algorithm with O(number of aliases), but most types have no or few aliases,
651        // so this should stay fast.
652        //
653        /// Returns `(aliases, ranges_where_Self_can_refer_to_our_type)`.
654        fn collect_possible_aliases(
655            sema: &Semantics<'_, RootDatabase>,
656            container: Adt,
657            exclude_library_files: bool,
658        ) -> Option<(FxHashSet<SmolStr>, Vec<FileRangeWrapper<EditionedFileId>>)> {
659            fn insert_type_alias(
660                db: &RootDatabase,
661                to_process: &mut Vec<(SmolStr, SearchScope)>,
662                alias_name: &str,
663                def: Definition<'_>,
664            ) {
665                let alias = alias_name.trim_start_matches("r#").to_smolstr();
666                tracing::debug!("found alias: {alias}");
667                to_process.push((alias, def.search_scope(db)));
668            }
669
670            let _p = tracing::info_span!("collect_possible_aliases").entered();
671
672            let db = sema.db;
673            let container_name = container.name(db).as_str().to_smolstr();
674            let search_scope = Definition::from(container).search_scope(db);
675            let mut seen = FxHashSet::default();
676            let mut completed = FxHashSet::default();
677            let mut to_process = vec![(container_name, search_scope)];
678            let mut is_possibly_self = Vec::new();
679            let mut total_files_searched = 0;
680
681            while let Some((current_to_process, current_to_process_search_scope)) = to_process.pop()
682            {
683                let is_alias = |alias: &ast::TypeAlias| {
684                    let def = sema.to_def(alias)?;
685                    let ty = def.ty(db);
686                    let is_alias = ty.as_adt()? == container;
687                    is_alias.then_some(def)
688                };
689
690                let finder = Finder::new(current_to_process.as_bytes());
691                for (file_text, file_id, search_range) in FindUsages::scope_files(
692                    db,
693                    &current_to_process_search_scope,
694                    exclude_library_files,
695                ) {
696                    let tree = LazyCell::new(move || sema.parse(file_id).syntax().clone());
697
698                    for offset in FindUsages::match_indices(&file_text, &finder, search_range) {
699                        let usages = FindUsages::find_nodes(
700                            sema,
701                            &current_to_process,
702                            file_id,
703                            &tree,
704                            offset,
705                        )
706                        .filter(|it| matches!(it.kind(), SyntaxKind::NAME | SyntaxKind::NAME_REF));
707                        for usage in usages {
708                            if let Some(alias) = usage.parent().and_then(|it| {
709                                let path = ast::PathSegment::cast(it)?.parent_path();
710                                let use_tree = ast::UseTree::cast(path.syntax().parent()?)?;
711                                use_tree.rename()?.name()
712                            }) {
713                                if seen.insert(InFileWrapper::new(
714                                    file_id,
715                                    alias.syntax().text_range(),
716                                )) {
717                                    tracing::debug!("found alias: {alias}");
718                                    cov_mark::hit!(container_use_rename);
719                                    // FIXME: `use`s have no easy way to determine their search scope, but they are rare.
720                                    to_process.push((
721                                        alias.text().to_smolstr(),
722                                        current_to_process_search_scope.clone(),
723                                    ));
724                                }
725                            } else if let Some(alias) =
726                                usage.ancestors().find_map(ast::TypeAlias::cast)
727                                && let Some(name) = alias.name()
728                                && seen
729                                    .insert(InFileWrapper::new(file_id, name.syntax().text_range()))
730                            {
731                                if let Some(def) = is_alias(&alias) {
732                                    cov_mark::hit!(container_type_alias);
733                                    insert_type_alias(
734                                        sema.db,
735                                        &mut to_process,
736                                        name.text(),
737                                        def.into(),
738                                    );
739                                } else {
740                                    cov_mark::hit!(same_name_different_def_type_alias);
741                                }
742                            }
743
744                            // We need to account for `Self`. It can only refer to our type inside an impl.
745                            let impl_ = 'impl_: {
746                                for ancestor in usage.ancestors() {
747                                    if let Some(parent) = ancestor.parent()
748                                        && let Some(parent) = ast::Impl::cast(parent)
749                                    {
750                                        // Only if the GENERIC_PARAM_LIST is directly under impl, otherwise it may be in the self ty.
751                                        if matches!(
752                                            ancestor.kind(),
753                                            SyntaxKind::ASSOC_ITEM_LIST
754                                                | SyntaxKind::WHERE_CLAUSE
755                                                | SyntaxKind::GENERIC_PARAM_LIST
756                                        ) {
757                                            break;
758                                        }
759                                        if parent
760                                            .trait_()
761                                            .is_some_and(|trait_| *trait_.syntax() == ancestor)
762                                        {
763                                            break;
764                                        }
765
766                                        // Otherwise, found an impl where its self ty may be our type.
767                                        break 'impl_ Some(parent);
768                                    }
769                                }
770                                None
771                            };
772                            (|| {
773                                let impl_ = impl_?;
774                                is_possibly_self.push(sema.original_range(impl_.syntax()));
775                                let assoc_items = impl_.assoc_item_list()?;
776                                let type_aliases = assoc_items
777                                    .syntax()
778                                    .descendants()
779                                    .filter_map(ast::TypeAlias::cast);
780                                for type_alias in type_aliases {
781                                    let Some(ty) = type_alias.ty() else { continue };
782                                    let Some(name) = type_alias.name() else { continue };
783                                    let contains_self = ty
784                                        .syntax()
785                                        .descendants_with_tokens()
786                                        .any(|node| node.kind() == SyntaxKind::SELF_TYPE_KW);
787                                    if !contains_self {
788                                        continue;
789                                    }
790                                    if seen.insert(InFileWrapper::new(
791                                        file_id,
792                                        name.syntax().text_range(),
793                                    )) {
794                                        if let Some(def) = is_alias(&type_alias) {
795                                            cov_mark::hit!(self_type_alias);
796                                            insert_type_alias(
797                                                sema.db,
798                                                &mut to_process,
799                                                name.text(),
800                                                def.into(),
801                                            );
802                                        } else {
803                                            cov_mark::hit!(same_name_different_def_type_alias);
804                                        }
805                                    }
806                                }
807                                Some(())
808                            })();
809                        }
810                    }
811                }
812
813                completed.insert(current_to_process);
814
815                total_files_searched += current_to_process_search_scope.entries.len();
816                // FIXME: Maybe this needs to be relative to the project size, or at least to the initial search scope?
817                if total_files_searched > 20_000 && completed.len() > 100 {
818                    // This case is extremely unlikely (even searching for `Vec::new()` on rust-analyzer does not enter
819                    // here - it searches less than 10,000 files, and it does so in five seconds), but if we get here,
820                    // we at a risk of entering an almost-infinite loop of growing the aliases list. So just stop and
821                    // let normal search handle this case.
822                    tracing::info!(aliases_count = %completed.len(), "too much aliases; leaving fast path");
823                    return None;
824                }
825            }
826
827            // Impls can contain each other, so we need to deduplicate their ranges.
828            is_possibly_self.sort_unstable_by_key(|position| {
829                (position.file_id, position.range.start(), Reverse(position.range.end()))
830            });
831            is_possibly_self.dedup_by(|pos2, pos1| {
832                pos1.file_id == pos2.file_id
833                    && pos1.range.start() <= pos2.range.start()
834                    && pos1.range.end() >= pos2.range.end()
835            });
836
837            tracing::info!(aliases_count = %completed.len(), "aliases search completed");
838
839            Some((completed, is_possibly_self))
840        }
841
842        fn search(
843            this: &FindUsages<'_, '_>,
844            finder: &Finder<'_>,
845            name: &str,
846            files: impl Iterator<Item = (Arc<str>, EditionedFileId, TextRange)>,
847            mut container_predicate: impl FnMut(
848                &SyntaxNode,
849                InFileWrapper<EditionedFileId, TextRange>,
850            ) -> bool,
851            sink: &mut dyn FnMut(EditionedFileId, FileReference) -> bool,
852        ) {
853            for (file_text, file_id, search_range) in files {
854                let tree = LazyCell::new(move || this.sema.parse(file_id).syntax().clone());
855
856                for offset in FindUsages::match_indices(&file_text, finder, search_range) {
857                    let usages = FindUsages::find_nodes(this.sema, name, file_id, &tree, offset)
858                        .filter_map(ast::NameRef::cast);
859                    for usage in usages {
860                        let found_usage = usage
861                            .syntax()
862                            .parent()
863                            .and_then(ast::PathSegment::cast)
864                            .map(|path_segment| {
865                                container_predicate(
866                                    path_segment.parent_path().syntax(),
867                                    InFileWrapper::new(file_id, usage.syntax().text_range()),
868                                )
869                            })
870                            .unwrap_or(false);
871                        if found_usage {
872                            this.found_name_ref(&usage, sink);
873                        }
874                    }
875                }
876            }
877        }
878
879        let Some((container_possible_aliases, is_possibly_self)) =
880            collect_possible_aliases(self.sema, container, self.exclude_library_files)
881        else {
882            return false;
883        };
884
885        cov_mark::hit!(short_associated_function_fast_search);
886
887        // FIXME: If Rust ever gains the ability to `use Struct::method` we'll also need to account for free
888        // functions.
889        let finder = Finder::new(name.as_bytes());
890        // The search for `Self` may return duplicate results with `ContainerName`, so deduplicate them.
891        let mut self_positions = FxHashSet::default();
892        tracing::info_span!("Self_search").in_scope(|| {
893            search(
894                self,
895                &finder,
896                name,
897                is_possibly_self.into_iter().map(|position| {
898                    (position.file_text(self.sema.db).clone(), position.file_id, position.range)
899                }),
900                |path, name_position| {
901                    let has_self = path
902                        .descendants_with_tokens()
903                        .any(|node| node.kind() == SyntaxKind::SELF_TYPE_KW);
904                    if has_self {
905                        self_positions.insert(name_position);
906                    }
907                    has_self
908                },
909                sink,
910            )
911        });
912        tracing::info_span!("aliases_search").in_scope(|| {
913            search(
914                self,
915                &finder,
916                name,
917                FindUsages::scope_files(self.sema.db, search_scope, self.exclude_library_files),
918                |path, name_position| {
919                    has_any_name(path, |name| container_possible_aliases.contains(name))
920                        && !self_positions.contains(&name_position)
921                },
922                sink,
923            )
924        });
925
926        true
927    }
928
929    pub fn search(&self, sink: &mut dyn FnMut(EditionedFileId, FileReference) -> bool) {
930        let _p = tracing::info_span!("FindUsages:search").entered();
931        let sema = self.sema;
932
933        let search_scope = {
934            // FIXME: Is the trait scope needed for trait impl assoc items?
935            let base =
936                as_trait_assoc_def(sema.db, self.def).unwrap_or(self.def).search_scope(sema.db);
937            match &self.scope {
938                None => base,
939                Some(scope) => base.intersection(scope),
940            }
941        };
942        if search_scope.entries.is_empty() {
943            return;
944        }
945
946        let name = match (self.rename, self.def) {
947            (Some(rename), _) => {
948                if rename.underscore_token().is_some() {
949                    None
950                } else {
951                    rename.name().map(|n| n.to_smolstr())
952                }
953            }
954            // special case crate modules as these do not have a proper name
955            (_, Definition::Module(module)) if module.is_crate_root(self.sema.db) => {
956                // FIXME: This assumes the crate name is always equal to its display name when it
957                // really isn't
958                // we should instead look at the dependency edge name and recursively search our way
959                // up the ancestors
960                module
961                    .krate(self.sema.db)
962                    .display_name(self.sema.db)
963                    .map(|crate_name| crate_name.crate_name().symbol().as_str().into())
964            }
965            _ => {
966                let self_kw_refs = || {
967                    self.include_self_kw_refs.as_ref().and_then(|ty| {
968                        ty.as_adt()
969                            .map(|adt| adt.name(self.sema.db))
970                            .or_else(|| ty.as_builtin().map(|builtin| builtin.name()))
971                    })
972                };
973                // We need to search without the `r#`, hence `as_str` access.
974                // We strip `'` from lifetimes and labels as otherwise they may not match with raw-escaped ones,
975                // e.g. if we search `'foo` we won't find `'r#foo`.
976                self.def
977                    .name(sema.db)
978                    .or_else(self_kw_refs)
979                    .map(|it| it.as_str().trim_start_matches('\'').to_smolstr())
980            }
981        };
982        let name = match &name {
983            Some(s) => s.as_str(),
984            None => return,
985        };
986
987        // FIXME: This should probably depend on the number of the results (specifically, the number of false results).
988        if name.len() <= 7 && self.short_associated_function_fast_search(sink, &search_scope, name)
989        {
990            return;
991        }
992
993        let finder = &Finder::new(name);
994        let include_self_kw_refs =
995            self.include_self_kw_refs.as_ref().map(|ty| (ty, Finder::new("Self")));
996        for (text, file_id, search_range) in
997            Self::scope_files(sema.db, &search_scope, self.exclude_library_files)
998        {
999            let tree = LazyCell::new(move || sema.parse(file_id).syntax().clone());
1000
1001            // Search for occurrences of the items name
1002            for offset in Self::match_indices(&text, finder, search_range) {
1003                let ret = tree.token_at_offset(offset).any(|token| {
1004                    if let Some((range, _frange, string_token, Some(nameres))) =
1005                        sema.check_for_format_args_template(token.clone(), offset)
1006                    {
1007                        return self.found_format_args_ref(
1008                            file_id,
1009                            range,
1010                            string_token,
1011                            nameres,
1012                            sink,
1013                        );
1014                    }
1015                    false
1016                });
1017                if ret {
1018                    return;
1019                }
1020
1021                for name in Self::find_nodes(sema, name, file_id, &tree, offset)
1022                    .filter_map(ast::NameLike::cast)
1023                {
1024                    if match name {
1025                        ast::NameLike::NameRef(name_ref) => self.found_name_ref(&name_ref, sink),
1026                        ast::NameLike::Name(name) => self.found_name(&name, sink),
1027                        ast::NameLike::Lifetime(lifetime) => self.found_lifetime(&lifetime, sink),
1028                    } {
1029                        return;
1030                    }
1031                }
1032            }
1033            // Search for occurrences of the `Self` referring to our type
1034            if let Some((self_ty, finder)) = &include_self_kw_refs {
1035                for offset in Self::match_indices(&text, finder, search_range) {
1036                    for name_ref in Self::find_nodes(sema, "Self", file_id, &tree, offset)
1037                        .filter_map(ast::NameRef::cast)
1038                    {
1039                        if self.found_self_ty_name_ref(self_ty, &name_ref, sink) {
1040                            return;
1041                        }
1042                    }
1043                }
1044            }
1045        }
1046
1047        // Search for `super` and `crate` resolving to our module
1048        if let Definition::Module(module) = self.def {
1049            let scope =
1050                search_scope.intersection(&SearchScope::module_and_children(self.sema.db, module));
1051
1052            let is_crate_root = module.is_crate_root(self.sema.db).then(|| Finder::new("crate"));
1053            let finder = &Finder::new("super");
1054
1055            for (text, file_id, search_range) in
1056                Self::scope_files(sema.db, &scope, self.exclude_library_files)
1057            {
1058                self.sema.db.unwind_if_revision_cancelled();
1059
1060                let tree = LazyCell::new(move || sema.parse(file_id).syntax().clone());
1061
1062                for offset in Self::match_indices(&text, finder, search_range) {
1063                    for name_ref in Self::find_nodes(sema, "super", file_id, &tree, offset)
1064                        .filter_map(ast::NameRef::cast)
1065                    {
1066                        if self.found_name_ref(&name_ref, sink) {
1067                            return;
1068                        }
1069                    }
1070                }
1071                if let Some(finder) = &is_crate_root {
1072                    for offset in Self::match_indices(&text, finder, search_range) {
1073                        for name_ref in Self::find_nodes(sema, "crate", file_id, &tree, offset)
1074                            .filter_map(ast::NameRef::cast)
1075                        {
1076                            if self.found_name_ref(&name_ref, sink) {
1077                                return;
1078                            }
1079                        }
1080                    }
1081                }
1082            }
1083        }
1084
1085        // search for module `self` references in our module's definition source
1086        match self.def {
1087            Definition::Module(module) if self.search_self_mod => {
1088                let src = module.definition_source(sema.db);
1089                let file_id = src.file_id.original_file(sema.db);
1090                let (file_id, search_range) = match src.value {
1091                    ModuleSource::Module(m) => (file_id, Some(m.syntax().text_range())),
1092                    ModuleSource::BlockExpr(b) => (file_id, Some(b.syntax().text_range())),
1093                    ModuleSource::SourceFile(_) => (file_id, None),
1094                };
1095
1096                let search_range = if let Some(&range) = search_scope.entries.get(&file_id) {
1097                    match (range, search_range) {
1098                        (None, range) | (range, None) => range,
1099                        (Some(range), Some(search_range)) => match range.intersect(search_range) {
1100                            Some(range) => Some(range),
1101                            None => return,
1102                        },
1103                    }
1104                } else {
1105                    return;
1106                };
1107
1108                let file_text = sema.db.file_text(file_id.file_id(self.sema.db));
1109                let text = file_text.text(sema.db);
1110                let search_range =
1111                    search_range.unwrap_or_else(|| TextRange::up_to(TextSize::of(&**text)));
1112
1113                let tree = LazyCell::new(|| sema.parse(file_id).syntax().clone());
1114                let finder = &Finder::new("self");
1115
1116                for offset in Self::match_indices(text, finder, search_range) {
1117                    for name_ref in Self::find_nodes(sema, "self", file_id, &tree, offset)
1118                        .filter_map(ast::NameRef::cast)
1119                    {
1120                        if self.found_self_module_name_ref(&name_ref, sink) {
1121                            return;
1122                        }
1123                    }
1124                }
1125            }
1126            _ => {}
1127        }
1128    }
1129
1130    fn found_self_ty_name_ref(
1131        &self,
1132        self_ty: &hir::Type<'_>,
1133        name_ref: &ast::NameRef,
1134        sink: &mut dyn FnMut(EditionedFileId, FileReference) -> bool,
1135    ) -> bool {
1136        if self.is_excluded_name_ref(name_ref) {
1137            return false;
1138        }
1139
1140        // See https://github.com/rust-lang/rust-analyzer/pull/15864/files/e0276dc5ddc38c65240edb408522bb869f15afb4#r1389848845
1141        let ty_eq = |ty: hir::Type<'_>| match (ty.as_adt(), self_ty.as_adt()) {
1142            (Some(ty), Some(self_ty)) => ty == self_ty,
1143            (None, None) => ty == *self_ty,
1144            _ => false,
1145        };
1146
1147        match NameRefClass::classify(self.sema, name_ref) {
1148            Some(NameRefClass::Definition(Definition::SelfType(impl_), _))
1149                if ty_eq(impl_.self_ty(self.sema.db)) =>
1150            {
1151                let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
1152                let reference = FileReference {
1153                    range,
1154                    name: FileReferenceNode::NameRef(name_ref.clone()),
1155                    category: ReferenceCategory::empty(),
1156                };
1157                sink(file_id, reference)
1158            }
1159            _ => false,
1160        }
1161    }
1162
1163    fn found_self_module_name_ref(
1164        &self,
1165        name_ref: &ast::NameRef,
1166        sink: &mut dyn FnMut(EditionedFileId, FileReference) -> bool,
1167    ) -> bool {
1168        if self.is_excluded_name_ref(name_ref) {
1169            return false;
1170        }
1171
1172        match NameRefClass::classify(self.sema, name_ref) {
1173            Some(NameRefClass::Definition(def @ Definition::Module(_), _)) if def == self.def => {
1174                let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
1175                let category = if is_name_ref_in_import(name_ref) {
1176                    ReferenceCategory::IMPORT
1177                } else {
1178                    ReferenceCategory::empty()
1179                };
1180                let reference = FileReference {
1181                    range,
1182                    name: FileReferenceNode::NameRef(name_ref.clone()),
1183                    category,
1184                };
1185                sink(file_id, reference)
1186            }
1187            _ => false,
1188        }
1189    }
1190
1191    fn found_format_args_ref(
1192        &self,
1193        file_id: EditionedFileId,
1194        range: TextRange,
1195        token: ast::String,
1196        res: Either<PathResolution<'db>, InlineAsmOperand>,
1197        sink: &mut dyn FnMut(EditionedFileId, FileReference) -> bool,
1198    ) -> bool {
1199        let def = res.either(Definition::from, Definition::from);
1200        if def == self.def {
1201            let reference = FileReference {
1202                range,
1203                name: FileReferenceNode::FormatStringEntry(token, range),
1204                category: ReferenceCategory::READ,
1205            };
1206            sink(file_id, reference)
1207        } else {
1208            false
1209        }
1210    }
1211
1212    fn found_lifetime(
1213        &self,
1214        lifetime: &ast::Lifetime,
1215        sink: &mut dyn FnMut(EditionedFileId, FileReference) -> bool,
1216    ) -> bool {
1217        match NameRefClass::classify_lifetime(self.sema, lifetime) {
1218            Some(NameRefClass::Definition(def, _)) if def == self.def => {
1219                let FileRange { file_id, range } = self.sema.original_range(lifetime.syntax());
1220                let reference = FileReference {
1221                    range,
1222                    name: FileReferenceNode::Lifetime(lifetime.clone()),
1223                    category: ReferenceCategory::empty(),
1224                };
1225                sink(file_id, reference)
1226            }
1227            _ => false,
1228        }
1229    }
1230
1231    fn found_name_ref(
1232        &self,
1233        name_ref: &ast::NameRef,
1234        sink: &mut dyn FnMut(EditionedFileId, FileReference) -> bool,
1235    ) -> bool {
1236        if self.is_excluded_name_ref(name_ref) {
1237            return false;
1238        }
1239
1240        match NameRefClass::classify(self.sema, name_ref) {
1241            Some(NameRefClass::Definition(def, _))
1242                if self.def == def
1243                    // is our def a trait assoc item? then we want to find all assoc items from trait impls of our trait
1244                    || matches!(self.assoc_item_container, Some(hir::AssocItemContainer::Trait(_)))
1245                        && convert_to_def_in_trait(self.sema.db, def) == self.def =>
1246            {
1247                let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
1248                let reference = FileReference {
1249                    range,
1250                    name: FileReferenceNode::NameRef(name_ref.clone()),
1251                    category: ReferenceCategory::new(self.sema, &def, name_ref),
1252                };
1253                sink(file_id, reference)
1254            }
1255            // FIXME: special case type aliases, we can't filter between impl and trait defs here as we lack the substitutions
1256            // so we always resolve all assoc type aliases to both their trait def and impl defs
1257            Some(NameRefClass::Definition(def, _))
1258                if self.assoc_item_container.is_some()
1259                    && matches!(self.def, Definition::TypeAlias(_))
1260                    && convert_to_def_in_trait(self.sema.db, def)
1261                        == convert_to_def_in_trait(self.sema.db, self.def) =>
1262            {
1263                let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
1264                let reference = FileReference {
1265                    range,
1266                    name: FileReferenceNode::NameRef(name_ref.clone()),
1267                    category: ReferenceCategory::new(self.sema, &def, name_ref),
1268                };
1269                sink(file_id, reference)
1270            }
1271            Some(NameRefClass::Definition(def, _))
1272                if self.include_self_kw_refs.is_some()
1273                    && self.include_self_kw_refs == def_to_ty(self.sema, &def) =>
1274            {
1275                let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
1276                let reference = FileReference {
1277                    range,
1278                    name: FileReferenceNode::NameRef(name_ref.clone()),
1279                    category: ReferenceCategory::new(self.sema, &def, name_ref),
1280                };
1281                sink(file_id, reference)
1282            }
1283            Some(NameRefClass::FieldShorthand {
1284                local_ref: local,
1285                field_ref: field,
1286                adt_subst: _,
1287            }) => {
1288                let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
1289
1290                let field = Definition::Field(field);
1291                let local = Definition::Local(local);
1292                let access = match self.def {
1293                    Definition::Field(_) if field == self.def => {
1294                        ReferenceCategory::new(self.sema, &field, name_ref)
1295                    }
1296                    Definition::Local(_) if local == self.def => {
1297                        ReferenceCategory::new(self.sema, &local, name_ref)
1298                    }
1299                    _ => return false,
1300                };
1301                let reference = FileReference {
1302                    range,
1303                    name: FileReferenceNode::NameRef(name_ref.clone()),
1304                    category: access,
1305                };
1306                sink(file_id, reference)
1307            }
1308            _ => false,
1309        }
1310    }
1311
1312    fn is_excluded_name_ref(&self, name_ref: &ast::NameRef) -> bool {
1313        (!self.included_categories.contains(ReferenceCategory::TEST)
1314            && is_name_ref_in_test(self.sema, name_ref))
1315            || (!self.included_categories.contains(ReferenceCategory::IMPORT)
1316                && is_name_ref_in_import(name_ref))
1317    }
1318
1319    fn found_name(
1320        &self,
1321        name: &ast::Name,
1322        sink: &mut dyn FnMut(EditionedFileId, FileReference) -> bool,
1323    ) -> bool {
1324        match NameClass::classify(self.sema, name) {
1325            Some(NameClass::PatFieldShorthand { local_def: _, field_ref, adt_subst: _ })
1326                if matches!(
1327                    self.def, Definition::Field(_) if Definition::Field(field_ref) == self.def
1328                ) =>
1329            {
1330                let FileRange { file_id, range } = self.sema.original_range(name.syntax());
1331                let reference = FileReference {
1332                    range,
1333                    name: FileReferenceNode::Name(name.clone()),
1334                    // FIXME: mutable patterns should have `Write` access
1335                    category: ReferenceCategory::READ,
1336                };
1337                sink(file_id, reference)
1338            }
1339            Some(NameClass::ConstReference(def)) if self.def == def => {
1340                let FileRange { file_id, range } = self.sema.original_range(name.syntax());
1341                let reference = FileReference {
1342                    range,
1343                    name: FileReferenceNode::Name(name.clone()),
1344                    category: ReferenceCategory::empty(),
1345                };
1346                sink(file_id, reference)
1347            }
1348            Some(NameClass::Definition(def)) if def != self.def => {
1349                match (&self.assoc_item_container, self.def) {
1350                    // for type aliases we always want to reference the trait def and all the trait impl counterparts
1351                    // FIXME: only until we can resolve them correctly, see FIXME above
1352                    (Some(_), Definition::TypeAlias(_))
1353                        if convert_to_def_in_trait(self.sema.db, def)
1354                            != convert_to_def_in_trait(self.sema.db, self.def) =>
1355                    {
1356                        return false;
1357                    }
1358                    (Some(_), Definition::TypeAlias(_)) => {}
1359                    // We looking at an assoc item of a trait definition, so reference all the
1360                    // corresponding assoc items belonging to this trait's trait implementations
1361                    (Some(hir::AssocItemContainer::Trait(_)), _)
1362                        if convert_to_def_in_trait(self.sema.db, def) == self.def => {}
1363                    _ => return false,
1364                }
1365                let FileRange { file_id, range } = self.sema.original_range(name.syntax());
1366                let reference = FileReference {
1367                    range,
1368                    name: FileReferenceNode::Name(name.clone()),
1369                    category: ReferenceCategory::empty(),
1370                };
1371                sink(file_id, reference)
1372            }
1373            _ => false,
1374        }
1375    }
1376}
1377
1378fn def_to_ty<'db>(
1379    sema: &Semantics<'db, RootDatabase>,
1380    def: &Definition<'db>,
1381) -> Option<hir::Type<'db>> {
1382    match def {
1383        Definition::Adt(adt) => Some(adt.ty(sema.db)),
1384        Definition::TypeAlias(it) => Some(it.ty(sema.db)),
1385        Definition::BuiltinType(it) => Some(it.ty(sema.db)),
1386        Definition::SelfType(it) => Some(it.self_ty(sema.db)),
1387        _ => None,
1388    }
1389}
1390
1391impl ReferenceCategory {
1392    fn new(
1393        sema: &Semantics<'_, RootDatabase>,
1394        def: &Definition<'_>,
1395        r: &ast::NameRef,
1396    ) -> ReferenceCategory {
1397        let mut result = ReferenceCategory::empty();
1398        if is_name_ref_in_test(sema, r) {
1399            result |= ReferenceCategory::TEST;
1400        }
1401
1402        // Only Locals and Fields have accesses for now.
1403        if !matches!(def, Definition::Local(_) | Definition::Field(_)) {
1404            if is_name_ref_in_import(r) {
1405                result |= ReferenceCategory::IMPORT;
1406            }
1407            return result;
1408        }
1409
1410        let mode = r.syntax().ancestors().find_map(|node| {
1411            match_ast! {
1412                match node {
1413                    ast::BinExpr(expr) => {
1414                        if matches!(expr.op_kind()?, ast::BinaryOp::Assignment { .. }) {
1415                            // If the variable or field ends on the LHS's end then it's a Write
1416                            // (covers fields and locals). FIXME: This is not terribly accurate.
1417                            if let Some(lhs) = expr.lhs()
1418                            && lhs.syntax().text_range().contains_range(r.syntax().text_range()) {
1419                                    return Some(ReferenceCategory::WRITE)
1420                                }
1421                        }
1422                        Some(ReferenceCategory::READ)
1423                    },
1424                    _ => None,
1425                }
1426            }
1427        }).unwrap_or(ReferenceCategory::READ);
1428
1429        result | mode
1430    }
1431}
1432
1433fn is_name_ref_in_import(name_ref: &ast::NameRef) -> bool {
1434    name_ref
1435        .syntax()
1436        .parent()
1437        .and_then(ast::PathSegment::cast)
1438        .and_then(|it| it.parent_path().top_path().syntax().parent())
1439        .is_some_and(|it| it.kind() == SyntaxKind::USE_TREE)
1440}
1441
1442fn is_name_ref_in_test(sema: &Semantics<'_, RootDatabase>, name_ref: &ast::NameRef) -> bool {
1443    sema.ancestors_with_macros(name_ref.syntax().clone()).any(|node| match ast::Fn::cast(node) {
1444        Some(it) => sema.to_def(&it).is_some_and(|func| func.is_test(sema.db)),
1445        None => false,
1446    })
1447}
1448
1449fn is_library_file(db: &RootDatabase, file_id: span::FileId) -> bool {
1450    let source_root = db.file_source_root(file_id).source_root_id(db);
1451    db.source_root(source_root).source_root(db).is_library
1452}