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