]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/ide-db/src/search.rs
Auto merge of #100581 - joboet:sync_rwlock_everywhere, r=thomcc
[rust.git] / src / tools / rust-analyzer / crates / ide-db / src / 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 we confirm each match using precise
5 //! name resolution.
6
7 use std::{mem, sync::Arc};
8
9 use base_db::{FileId, FileRange, SourceDatabase, SourceDatabaseExt};
10 use hir::{DefWithBody, HasAttrs, HasSource, InFile, ModuleSource, Semantics, Visibility};
11 use memchr::memmem::Finder;
12 use once_cell::unsync::Lazy;
13 use parser::SyntaxKind;
14 use stdx::hash::NoHashHashMap;
15 use syntax::{ast, match_ast, AstNode, TextRange, TextSize};
16
17 use crate::{
18     defs::{Definition, NameClass, NameRefClass},
19     traits::{as_trait_assoc_def, convert_to_def_in_trait},
20     RootDatabase,
21 };
22
23 #[derive(Debug, Default, Clone)]
24 pub struct UsageSearchResult {
25     pub references: NoHashHashMap<FileId, Vec<FileReference>>,
26 }
27
28 impl UsageSearchResult {
29     pub fn is_empty(&self) -> bool {
30         self.references.is_empty()
31     }
32
33     pub fn len(&self) -> usize {
34         self.references.len()
35     }
36
37     pub fn iter(&self) -> impl Iterator<Item = (&FileId, &[FileReference])> + '_ {
38         self.references.iter().map(|(file_id, refs)| (file_id, &**refs))
39     }
40
41     pub fn file_ranges(&self) -> impl Iterator<Item = FileRange> + '_ {
42         self.references.iter().flat_map(|(&file_id, refs)| {
43             refs.iter().map(move |&FileReference { range, .. }| FileRange { file_id, range })
44         })
45     }
46 }
47
48 impl IntoIterator for UsageSearchResult {
49     type Item = (FileId, Vec<FileReference>);
50     type IntoIter = <NoHashHashMap<FileId, Vec<FileReference>> as IntoIterator>::IntoIter;
51
52     fn into_iter(self) -> Self::IntoIter {
53         self.references.into_iter()
54     }
55 }
56
57 #[derive(Debug, Clone)]
58 pub struct FileReference {
59     /// The range of the reference in the original file
60     pub range: TextRange,
61     /// The node of the reference in the (macro-)file
62     pub name: ast::NameLike,
63     pub category: Option<ReferenceCategory>,
64 }
65
66 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
67 pub enum ReferenceCategory {
68     // FIXME: Add this variant and delete the `retain_adt_literal_usages` function.
69     // Create
70     Write,
71     Read,
72     Import,
73     // FIXME: Some day should be able to search in doc comments. Would probably
74     // need to switch from enum to bitflags then?
75     // DocComment
76 }
77
78 /// Generally, `search_scope` returns files that might contain references for the element.
79 /// For `pub(crate)` things it's a crate, for `pub` things it's a crate and dependant crates.
80 /// In some cases, the location of the references is known to within a `TextRange`,
81 /// e.g. for things like local variables.
82 #[derive(Clone, Debug)]
83 pub struct SearchScope {
84     entries: NoHashHashMap<FileId, Option<TextRange>>,
85 }
86
87 impl SearchScope {
88     fn new(entries: NoHashHashMap<FileId, Option<TextRange>>) -> SearchScope {
89         SearchScope { entries }
90     }
91
92     /// Build a search scope spanning the entire crate graph of files.
93     fn crate_graph(db: &RootDatabase) -> SearchScope {
94         let mut entries = NoHashHashMap::default();
95
96         let graph = db.crate_graph();
97         for krate in graph.iter() {
98             let root_file = graph[krate].root_file_id;
99             let source_root_id = db.file_source_root(root_file);
100             let source_root = db.source_root(source_root_id);
101             entries.extend(source_root.iter().map(|id| (id, None)));
102         }
103         SearchScope { entries }
104     }
105
106     /// Build a search scope spanning all the reverse dependencies of the given crate.
107     fn reverse_dependencies(db: &RootDatabase, of: hir::Crate) -> SearchScope {
108         let mut entries = NoHashHashMap::default();
109         for rev_dep in of.transitive_reverse_dependencies(db) {
110             let root_file = rev_dep.root_file(db);
111             let source_root_id = db.file_source_root(root_file);
112             let source_root = db.source_root(source_root_id);
113             entries.extend(source_root.iter().map(|id| (id, None)));
114         }
115         SearchScope { entries }
116     }
117
118     /// Build a search scope spanning the given crate.
119     fn krate(db: &RootDatabase, of: hir::Crate) -> SearchScope {
120         let root_file = of.root_file(db);
121         let source_root_id = db.file_source_root(root_file);
122         let source_root = db.source_root(source_root_id);
123         SearchScope { entries: source_root.iter().map(|id| (id, None)).collect() }
124     }
125
126     /// Build a search scope spanning the given module and all its submodules.
127     fn module_and_children(db: &RootDatabase, module: hir::Module) -> SearchScope {
128         let mut entries = NoHashHashMap::default();
129
130         let (file_id, range) = {
131             let InFile { file_id, value } = module.definition_source(db);
132             if let Some((file_id, call_source)) = file_id.original_call_node(db) {
133                 (file_id, Some(call_source.text_range()))
134             } else {
135                 (
136                     file_id.original_file(db),
137                     match value {
138                         ModuleSource::SourceFile(_) => None,
139                         ModuleSource::Module(it) => Some(it.syntax().text_range()),
140                         ModuleSource::BlockExpr(it) => Some(it.syntax().text_range()),
141                     },
142                 )
143             }
144         };
145         entries.insert(file_id, range);
146
147         let mut to_visit: Vec<_> = module.children(db).collect();
148         while let Some(module) = to_visit.pop() {
149             if let InFile { file_id, value: ModuleSource::SourceFile(_) } =
150                 module.definition_source(db)
151             {
152                 entries.insert(file_id.original_file(db), None);
153             }
154             to_visit.extend(module.children(db));
155         }
156         SearchScope { entries }
157     }
158
159     /// Build an empty search scope.
160     pub fn empty() -> SearchScope {
161         SearchScope::new(NoHashHashMap::default())
162     }
163
164     /// Build a empty search scope spanning the given file.
165     pub fn single_file(file: FileId) -> SearchScope {
166         SearchScope::new(std::iter::once((file, None)).collect())
167     }
168
169     /// Build a empty search scope spanning the text range of the given file.
170     pub fn file_range(range: FileRange) -> SearchScope {
171         SearchScope::new(std::iter::once((range.file_id, Some(range.range))).collect())
172     }
173
174     /// Build a empty search scope spanning the given files.
175     pub fn files(files: &[FileId]) -> SearchScope {
176         SearchScope::new(files.iter().map(|f| (*f, None)).collect())
177     }
178
179     pub fn intersection(&self, other: &SearchScope) -> SearchScope {
180         let (mut small, mut large) = (&self.entries, &other.entries);
181         if small.len() > large.len() {
182             mem::swap(&mut small, &mut large)
183         }
184
185         let intersect_ranges =
186             |r1: Option<TextRange>, r2: Option<TextRange>| -> Option<Option<TextRange>> {
187                 match (r1, r2) {
188                     (None, r) | (r, None) => Some(r),
189                     (Some(r1), Some(r2)) => r1.intersect(r2).map(Some),
190                 }
191             };
192         let res = small
193             .iter()
194             .filter_map(|(&file_id, &r1)| {
195                 let &r2 = large.get(&file_id)?;
196                 let r = intersect_ranges(r1, r2)?;
197                 Some((file_id, r))
198             })
199             .collect();
200
201         SearchScope::new(res)
202     }
203 }
204
205 impl IntoIterator for SearchScope {
206     type Item = (FileId, Option<TextRange>);
207     type IntoIter = std::collections::hash_map::IntoIter<FileId, Option<TextRange>>;
208
209     fn into_iter(self) -> Self::IntoIter {
210         self.entries.into_iter()
211     }
212 }
213
214 impl Definition {
215     fn search_scope(&self, db: &RootDatabase) -> SearchScope {
216         let _p = profile::span("search_scope");
217
218         if let Definition::BuiltinType(_) = self {
219             return SearchScope::crate_graph(db);
220         }
221
222         // def is crate root
223         // FIXME: We don't do searches for crates currently, as a crate does not actually have a single name
224         if let &Definition::Module(module) = self {
225             if module.is_crate_root(db) {
226                 return SearchScope::reverse_dependencies(db, module.krate());
227             }
228         }
229
230         let module = match self.module(db) {
231             Some(it) => it,
232             None => return SearchScope::empty(),
233         };
234         let InFile { file_id, value: module_source } = module.definition_source(db);
235         let file_id = file_id.original_file(db);
236
237         if let Definition::Local(var) = self {
238             let def = match var.parent(db) {
239                 DefWithBody::Function(f) => f.source(db).map(|src| src.syntax().cloned()),
240                 DefWithBody::Const(c) => c.source(db).map(|src| src.syntax().cloned()),
241                 DefWithBody::Static(s) => s.source(db).map(|src| src.syntax().cloned()),
242             };
243             return match def {
244                 Some(def) => SearchScope::file_range(def.as_ref().original_file_range(db)),
245                 None => SearchScope::single_file(file_id),
246             };
247         }
248
249         if let Definition::SelfType(impl_) = self {
250             return match impl_.source(db).map(|src| src.syntax().cloned()) {
251                 Some(def) => SearchScope::file_range(def.as_ref().original_file_range(db)),
252                 None => SearchScope::single_file(file_id),
253             };
254         }
255
256         if let Definition::GenericParam(hir::GenericParam::LifetimeParam(param)) = self {
257             let def = match param.parent(db) {
258                 hir::GenericDef::Function(it) => it.source(db).map(|src| src.syntax().cloned()),
259                 hir::GenericDef::Adt(it) => it.source(db).map(|src| src.syntax().cloned()),
260                 hir::GenericDef::Trait(it) => it.source(db).map(|src| src.syntax().cloned()),
261                 hir::GenericDef::TypeAlias(it) => it.source(db).map(|src| src.syntax().cloned()),
262                 hir::GenericDef::Impl(it) => it.source(db).map(|src| src.syntax().cloned()),
263                 hir::GenericDef::Variant(it) => it.source(db).map(|src| src.syntax().cloned()),
264                 hir::GenericDef::Const(it) => it.source(db).map(|src| src.syntax().cloned()),
265             };
266             return match def {
267                 Some(def) => SearchScope::file_range(def.as_ref().original_file_range(db)),
268                 None => SearchScope::single_file(file_id),
269             };
270         }
271
272         if let Definition::Macro(macro_def) = self {
273             return match macro_def.kind(db) {
274                 hir::MacroKind::Declarative => {
275                     if macro_def.attrs(db).by_key("macro_export").exists() {
276                         SearchScope::reverse_dependencies(db, module.krate())
277                     } else {
278                         SearchScope::krate(db, module.krate())
279                     }
280                 }
281                 hir::MacroKind::BuiltIn => SearchScope::crate_graph(db),
282                 hir::MacroKind::Derive | hir::MacroKind::Attr | hir::MacroKind::ProcMacro => {
283                     SearchScope::reverse_dependencies(db, module.krate())
284                 }
285             };
286         }
287
288         if let Definition::DeriveHelper(_) = self {
289             return SearchScope::reverse_dependencies(db, module.krate());
290         }
291
292         let vis = self.visibility(db);
293         if let Some(Visibility::Public) = vis {
294             return SearchScope::reverse_dependencies(db, module.krate());
295         }
296         if let Some(Visibility::Module(module)) = vis {
297             return SearchScope::module_and_children(db, module.into());
298         }
299
300         let range = match module_source {
301             ModuleSource::Module(m) => Some(m.syntax().text_range()),
302             ModuleSource::BlockExpr(b) => Some(b.syntax().text_range()),
303             ModuleSource::SourceFile(_) => None,
304         };
305         match range {
306             Some(range) => SearchScope::file_range(FileRange { file_id, range }),
307             None => SearchScope::single_file(file_id),
308         }
309     }
310
311     pub fn usages<'a>(self, sema: &'a Semantics<'_, RootDatabase>) -> FindUsages<'a> {
312         FindUsages {
313             local_repr: match self {
314                 Definition::Local(local) => Some(local.representative(sema.db)),
315                 _ => None,
316             },
317             def: self,
318             trait_assoc_def: as_trait_assoc_def(sema.db, self),
319             sema,
320             scope: None,
321             include_self_kw_refs: None,
322             search_self_mod: false,
323         }
324     }
325 }
326
327 #[derive(Clone)]
328 pub struct FindUsages<'a> {
329     def: Definition,
330     /// If def is an assoc item from a trait or trait impl, this is the corresponding item of the trait definition
331     trait_assoc_def: Option<Definition>,
332     sema: &'a Semantics<'a, RootDatabase>,
333     scope: Option<SearchScope>,
334     include_self_kw_refs: Option<hir::Type>,
335     local_repr: Option<hir::Local>,
336     search_self_mod: bool,
337 }
338
339 impl<'a> FindUsages<'a> {
340     /// Enable searching for `Self` when the definition is a type or `self` for modules.
341     pub fn include_self_refs(mut self) -> FindUsages<'a> {
342         self.include_self_kw_refs = def_to_ty(self.sema, &self.def);
343         self.search_self_mod = true;
344         self
345     }
346
347     /// Limit the search to a given [`SearchScope`].
348     pub fn in_scope(self, scope: SearchScope) -> FindUsages<'a> {
349         self.set_scope(Some(scope))
350     }
351
352     /// Limit the search to a given [`SearchScope`].
353     pub fn set_scope(mut self, scope: Option<SearchScope>) -> FindUsages<'a> {
354         assert!(self.scope.is_none());
355         self.scope = scope;
356         self
357     }
358
359     pub fn at_least_one(&self) -> bool {
360         let mut found = false;
361         self.search(&mut |_, _| {
362             found = true;
363             true
364         });
365         found
366     }
367
368     pub fn all(self) -> UsageSearchResult {
369         let mut res = UsageSearchResult::default();
370         self.search(&mut |file_id, reference| {
371             res.references.entry(file_id).or_default().push(reference);
372             false
373         });
374         res
375     }
376
377     fn search(&self, sink: &mut dyn FnMut(FileId, FileReference) -> bool) {
378         let _p = profile::span("FindUsages:search");
379         let sema = self.sema;
380
381         let search_scope = {
382             let base = self.trait_assoc_def.unwrap_or(self.def).search_scope(sema.db);
383             match &self.scope {
384                 None => base,
385                 Some(scope) => base.intersection(scope),
386             }
387         };
388
389         let name = match self.def {
390             // special case crate modules as these do not have a proper name
391             Definition::Module(module) if module.is_crate_root(self.sema.db) => {
392                 // FIXME: This assumes the crate name is always equal to its display name when it really isn't
393                 module
394                     .krate()
395                     .display_name(self.sema.db)
396                     .map(|crate_name| crate_name.crate_name().as_smol_str().clone())
397             }
398             _ => {
399                 let self_kw_refs = || {
400                     self.include_self_kw_refs.as_ref().and_then(|ty| {
401                         ty.as_adt()
402                             .map(|adt| adt.name(self.sema.db))
403                             .or_else(|| ty.as_builtin().map(|builtin| builtin.name()))
404                     })
405                 };
406                 // We need to unescape the name in case it is written without "r#" in earlier
407                 // editions of Rust where it isn't a keyword.
408                 self.def.name(sema.db).or_else(self_kw_refs).map(|it| it.unescaped().to_smol_str())
409             }
410         };
411         let name = match &name {
412             Some(s) => s.as_str(),
413             None => return,
414         };
415         let finder = &Finder::new(name);
416         let include_self_kw_refs =
417             self.include_self_kw_refs.as_ref().map(|ty| (ty, Finder::new("Self")));
418
419         // for<'a> |text: &'a str, name: &'a str, search_range: TextRange| -> impl Iterator<Item = TextSize> + 'a { ... }
420         fn match_indices<'a>(
421             text: &'a str,
422             finder: &'a Finder<'a>,
423             search_range: TextRange,
424         ) -> impl Iterator<Item = TextSize> + 'a {
425             finder.find_iter(text.as_bytes()).filter_map(move |idx| {
426                 let offset: TextSize = idx.try_into().unwrap();
427                 if !search_range.contains_inclusive(offset) {
428                     return None;
429                 }
430                 Some(offset)
431             })
432         }
433
434         // for<'a> |scope: &'a SearchScope| -> impl Iterator<Item = (Arc<String>, FileId, TextRange)> + 'a { ... }
435         fn scope_files<'a>(
436             sema: &'a Semantics<'_, RootDatabase>,
437             scope: &'a SearchScope,
438         ) -> impl Iterator<Item = (Arc<String>, FileId, TextRange)> + 'a {
439             scope.entries.iter().map(|(&file_id, &search_range)| {
440                 let text = sema.db.file_text(file_id);
441                 let search_range =
442                     search_range.unwrap_or_else(|| TextRange::up_to(TextSize::of(text.as_str())));
443
444                 (text, file_id, search_range)
445             })
446         }
447
448         // FIXME: There should be optimization potential here
449         // Currently we try to descend everything we find which
450         // means we call `Semantics::descend_into_macros` on
451         // every textual hit. That function is notoriously
452         // expensive even for things that do not get down mapped
453         // into macros.
454         for (text, file_id, search_range) in scope_files(sema, &search_scope) {
455             let tree = Lazy::new(move || sema.parse(file_id).syntax().clone());
456
457             // Search for occurrences of the items name
458             for offset in match_indices(&text, finder, search_range) {
459                 for name in sema.find_nodes_at_offset_with_descend(&tree, offset) {
460                     if match name {
461                         ast::NameLike::NameRef(name_ref) => self.found_name_ref(&name_ref, sink),
462                         ast::NameLike::Name(name) => self.found_name(&name, sink),
463                         ast::NameLike::Lifetime(lifetime) => self.found_lifetime(&lifetime, sink),
464                     } {
465                         return;
466                     }
467                 }
468             }
469             // Search for occurrences of the `Self` referring to our type
470             if let Some((self_ty, finder)) = &include_self_kw_refs {
471                 for offset in match_indices(&text, finder, search_range) {
472                     for name_ref in sema.find_nodes_at_offset_with_descend(&tree, offset) {
473                         if self.found_self_ty_name_ref(self_ty, &name_ref, sink) {
474                             return;
475                         }
476                     }
477                 }
478             }
479         }
480
481         // Search for `super` and `crate` resolving to our module
482         match self.def {
483             Definition::Module(module) => {
484                 let scope = search_scope
485                     .intersection(&SearchScope::module_and_children(self.sema.db, module));
486
487                 let is_crate_root =
488                     module.is_crate_root(self.sema.db).then(|| Finder::new("crate"));
489                 let finder = &Finder::new("super");
490
491                 for (text, file_id, search_range) in scope_files(sema, &scope) {
492                     let tree = Lazy::new(move || sema.parse(file_id).syntax().clone());
493
494                     for offset in match_indices(&text, finder, search_range) {
495                         for name_ref in sema.find_nodes_at_offset_with_descend(&tree, offset) {
496                             if self.found_name_ref(&name_ref, sink) {
497                                 return;
498                             }
499                         }
500                     }
501                     if let Some(finder) = &is_crate_root {
502                         for offset in match_indices(&text, finder, search_range) {
503                             for name_ref in sema.find_nodes_at_offset_with_descend(&tree, offset) {
504                                 if self.found_name_ref(&name_ref, sink) {
505                                     return;
506                                 }
507                             }
508                         }
509                     }
510                 }
511             }
512             _ => (),
513         }
514
515         // search for module `self` references in our module's definition source
516         match self.def {
517             Definition::Module(module) if self.search_self_mod => {
518                 let src = module.definition_source(sema.db);
519                 let file_id = src.file_id.original_file(sema.db);
520                 let (file_id, search_range) = match src.value {
521                     ModuleSource::Module(m) => (file_id, Some(m.syntax().text_range())),
522                     ModuleSource::BlockExpr(b) => (file_id, Some(b.syntax().text_range())),
523                     ModuleSource::SourceFile(_) => (file_id, None),
524                 };
525
526                 let search_range = if let Some(&range) = search_scope.entries.get(&file_id) {
527                     match (range, search_range) {
528                         (None, range) | (range, None) => range,
529                         (Some(range), Some(search_range)) => match range.intersect(search_range) {
530                             Some(range) => Some(range),
531                             None => return,
532                         },
533                     }
534                 } else {
535                     return;
536                 };
537
538                 let text = sema.db.file_text(file_id);
539                 let search_range =
540                     search_range.unwrap_or_else(|| TextRange::up_to(TextSize::of(text.as_str())));
541
542                 let tree = Lazy::new(|| sema.parse(file_id).syntax().clone());
543                 let finder = &Finder::new("self");
544
545                 for offset in match_indices(&text, finder, search_range) {
546                     for name_ref in sema.find_nodes_at_offset_with_descend(&tree, offset) {
547                         if self.found_self_module_name_ref(&name_ref, sink) {
548                             return;
549                         }
550                     }
551                 }
552             }
553             _ => {}
554         }
555     }
556
557     fn found_self_ty_name_ref(
558         &self,
559         self_ty: &hir::Type,
560         name_ref: &ast::NameRef,
561         sink: &mut dyn FnMut(FileId, FileReference) -> bool,
562     ) -> bool {
563         match NameRefClass::classify(self.sema, name_ref) {
564             Some(NameRefClass::Definition(Definition::SelfType(impl_)))
565                 if impl_.self_ty(self.sema.db) == *self_ty =>
566             {
567                 let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
568                 let reference = FileReference {
569                     range,
570                     name: ast::NameLike::NameRef(name_ref.clone()),
571                     category: None,
572                 };
573                 sink(file_id, reference)
574             }
575             _ => false,
576         }
577     }
578
579     fn found_self_module_name_ref(
580         &self,
581         name_ref: &ast::NameRef,
582         sink: &mut dyn FnMut(FileId, FileReference) -> bool,
583     ) -> bool {
584         match NameRefClass::classify(self.sema, name_ref) {
585             Some(NameRefClass::Definition(def @ Definition::Module(_))) if def == self.def => {
586                 let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
587                 let reference = FileReference {
588                     range,
589                     name: ast::NameLike::NameRef(name_ref.clone()),
590                     category: is_name_ref_in_import(name_ref).then(|| ReferenceCategory::Import),
591                 };
592                 sink(file_id, reference)
593             }
594             _ => false,
595         }
596     }
597
598     fn found_lifetime(
599         &self,
600         lifetime: &ast::Lifetime,
601         sink: &mut dyn FnMut(FileId, FileReference) -> bool,
602     ) -> bool {
603         match NameRefClass::classify_lifetime(self.sema, lifetime) {
604             Some(NameRefClass::Definition(def)) if def == self.def => {
605                 let FileRange { file_id, range } = self.sema.original_range(lifetime.syntax());
606                 let reference = FileReference {
607                     range,
608                     name: ast::NameLike::Lifetime(lifetime.clone()),
609                     category: None,
610                 };
611                 sink(file_id, reference)
612             }
613             _ => false,
614         }
615     }
616
617     fn found_name_ref(
618         &self,
619         name_ref: &ast::NameRef,
620         sink: &mut dyn FnMut(FileId, FileReference) -> bool,
621     ) -> bool {
622         match NameRefClass::classify(self.sema, name_ref) {
623             Some(NameRefClass::Definition(def @ Definition::Local(local)))
624                 if matches!(
625                     self.local_repr, Some(repr) if repr == local.representative(self.sema.db)
626                 ) =>
627             {
628                 let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
629                 let reference = FileReference {
630                     range,
631                     name: ast::NameLike::NameRef(name_ref.clone()),
632                     category: ReferenceCategory::new(&def, name_ref),
633                 };
634                 sink(file_id, reference)
635             }
636             Some(NameRefClass::Definition(def))
637                 if match self.trait_assoc_def {
638                     Some(trait_assoc_def) => {
639                         // we have a trait assoc item, so force resolve all assoc items to their trait version
640                         convert_to_def_in_trait(self.sema.db, def) == trait_assoc_def
641                     }
642                     None => self.def == def,
643                 } =>
644             {
645                 let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
646                 let reference = FileReference {
647                     range,
648                     name: ast::NameLike::NameRef(name_ref.clone()),
649                     category: ReferenceCategory::new(&def, name_ref),
650                 };
651                 sink(file_id, reference)
652             }
653             Some(NameRefClass::Definition(def)) if self.include_self_kw_refs.is_some() => {
654                 if self.include_self_kw_refs == def_to_ty(self.sema, &def) {
655                     let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
656                     let reference = FileReference {
657                         range,
658                         name: ast::NameLike::NameRef(name_ref.clone()),
659                         category: ReferenceCategory::new(&def, name_ref),
660                     };
661                     sink(file_id, reference)
662                 } else {
663                     false
664                 }
665             }
666             Some(NameRefClass::FieldShorthand { local_ref: local, field_ref: field }) => {
667                 let field = Definition::Field(field);
668                 let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
669                 let access = match self.def {
670                     Definition::Field(_) if field == self.def => {
671                         ReferenceCategory::new(&field, name_ref)
672                     }
673                     Definition::Local(_) if matches!(self.local_repr, Some(repr) if repr == local.representative(self.sema.db)) => {
674                         ReferenceCategory::new(&Definition::Local(local), name_ref)
675                     }
676                     _ => return false,
677                 };
678                 let reference = FileReference {
679                     range,
680                     name: ast::NameLike::NameRef(name_ref.clone()),
681                     category: access,
682                 };
683                 sink(file_id, reference)
684             }
685             _ => false,
686         }
687     }
688
689     fn found_name(
690         &self,
691         name: &ast::Name,
692         sink: &mut dyn FnMut(FileId, FileReference) -> bool,
693     ) -> bool {
694         match NameClass::classify(self.sema, name) {
695             Some(NameClass::PatFieldShorthand { local_def: _, field_ref })
696                 if matches!(
697                     self.def, Definition::Field(_) if Definition::Field(field_ref) == self.def
698                 ) =>
699             {
700                 let FileRange { file_id, range } = self.sema.original_range(name.syntax());
701                 let reference = FileReference {
702                     range,
703                     name: ast::NameLike::Name(name.clone()),
704                     // FIXME: mutable patterns should have `Write` access
705                     category: Some(ReferenceCategory::Read),
706                 };
707                 sink(file_id, reference)
708             }
709             Some(NameClass::ConstReference(def)) if self.def == def => {
710                 let FileRange { file_id, range } = self.sema.original_range(name.syntax());
711                 let reference = FileReference {
712                     range,
713                     name: ast::NameLike::Name(name.clone()),
714                     category: None,
715                 };
716                 sink(file_id, reference)
717             }
718             Some(NameClass::Definition(def @ Definition::Local(local))) if def != self.def => {
719                 if matches!(
720                     self.local_repr,
721                     Some(repr) if local.representative(self.sema.db) == repr
722                 ) {
723                     let FileRange { file_id, range } = self.sema.original_range(name.syntax());
724                     let reference = FileReference {
725                         range,
726                         name: ast::NameLike::Name(name.clone()),
727                         category: None,
728                     };
729                     return sink(file_id, reference);
730                 }
731                 false
732             }
733             Some(NameClass::Definition(def)) if def != self.def => {
734                 // if the def we are looking for is a trait (impl) assoc item, we'll have to resolve the items to trait definition assoc item
735                 if !matches!(
736                     self.trait_assoc_def,
737                     Some(trait_assoc_def)
738                         if convert_to_def_in_trait(self.sema.db, def) == trait_assoc_def
739                 ) {
740                     return false;
741                 }
742                 let FileRange { file_id, range } = self.sema.original_range(name.syntax());
743                 let reference = FileReference {
744                     range,
745                     name: ast::NameLike::Name(name.clone()),
746                     category: None,
747                 };
748                 sink(file_id, reference)
749             }
750             _ => false,
751         }
752     }
753 }
754
755 fn def_to_ty(sema: &Semantics<'_, RootDatabase>, def: &Definition) -> Option<hir::Type> {
756     match def {
757         Definition::Adt(adt) => Some(adt.ty(sema.db)),
758         Definition::TypeAlias(it) => Some(it.ty(sema.db)),
759         Definition::BuiltinType(it) => Some(it.ty(sema.db)),
760         Definition::SelfType(it) => Some(it.self_ty(sema.db)),
761         _ => None,
762     }
763 }
764
765 impl ReferenceCategory {
766     fn new(def: &Definition, r: &ast::NameRef) -> Option<ReferenceCategory> {
767         // Only Locals and Fields have accesses for now.
768         if !matches!(def, Definition::Local(_) | Definition::Field(_)) {
769             return is_name_ref_in_import(r).then(|| ReferenceCategory::Import);
770         }
771
772         let mode = r.syntax().ancestors().find_map(|node| {
773         match_ast! {
774             match node {
775                 ast::BinExpr(expr) => {
776                     if matches!(expr.op_kind()?, ast::BinaryOp::Assignment { .. }) {
777                         // If the variable or field ends on the LHS's end then it's a Write (covers fields and locals).
778                         // FIXME: This is not terribly accurate.
779                         if let Some(lhs) = expr.lhs() {
780                             if lhs.syntax().text_range().end() == r.syntax().text_range().end() {
781                                 return Some(ReferenceCategory::Write);
782                             }
783                         }
784                     }
785                     Some(ReferenceCategory::Read)
786                 },
787                 _ => None
788             }
789         }
790     });
791
792         // Default Locals and Fields to read
793         mode.or(Some(ReferenceCategory::Read))
794     }
795 }
796
797 fn is_name_ref_in_import(name_ref: &ast::NameRef) -> bool {
798     name_ref
799         .syntax()
800         .parent()
801         .and_then(ast::PathSegment::cast)
802         .and_then(|it| it.parent_path().top_path().syntax().parent())
803         .map_or(false, |it| it.kind() == SyntaxKind::USE_TREE)
804 }