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