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