1 //! Implementation of find-usages functionality.
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
7 use std::{convert::TryInto, mem};
9 use base_db::{FileId, FileRange, SourceDatabaseExt};
10 use hir::{DefWithBody, HasSource, Module, ModuleSource, Semantics, Visibility};
11 use once_cell::unsync::Lazy;
12 use rustc_hash::FxHashMap;
13 use syntax::{ast, match_ast, AstNode, TextRange, TextSize};
15 use crate::defs::NameClass;
17 defs::{Definition, NameRefClass},
21 #[derive(Debug, Default, Clone)]
22 pub struct UsageSearchResult {
23 pub references: FxHashMap<FileId, Vec<FileReference>>,
26 impl UsageSearchResult {
27 pub fn is_empty(&self) -> bool {
28 self.references.is_empty()
31 pub fn len(&self) -> usize {
35 pub fn iter(&self) -> impl Iterator<Item = (&FileId, &Vec<FileReference>)> + '_ {
36 self.references.iter()
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 })
46 impl IntoIterator for UsageSearchResult {
47 type Item = (FileId, Vec<FileReference>);
48 type IntoIter = <FxHashMap<FileId, Vec<FileReference>> as IntoIterator>::IntoIter;
50 fn into_iter(self) -> Self::IntoIter {
51 self.references.into_iter()
55 #[derive(Debug, Clone)]
57 NameRef(ast::NameRef),
59 Lifetime(ast::Lifetime),
63 pub fn as_name_ref(&self) -> Option<&ast::NameRef> {
65 NameLike::NameRef(name_ref) => Some(name_ref),
73 ast::{Lifetime, Name, NameRef},
76 stdx::impl_from!(NameRef, Name, Lifetime for NameLike);
79 #[derive(Debug, Clone)]
80 pub struct FileReference {
83 pub access: Option<ReferenceAccess>,
86 #[derive(Debug, Copy, Clone, PartialEq)]
87 pub enum ReferenceAccess {
92 /// Generally, `search_scope` returns files that might contain references for the element.
93 /// For `pub(crate)` things it's a crate, for `pub` things it's a crate and dependant crates.
94 /// In some cases, the location of the references is known to within a `TextRange`,
95 /// e.g. for things like local variables.
96 pub struct SearchScope {
97 entries: FxHashMap<FileId, Option<TextRange>>,
101 fn new(entries: FxHashMap<FileId, Option<TextRange>>) -> SearchScope {
102 SearchScope { entries }
105 pub fn empty() -> SearchScope {
106 SearchScope::new(FxHashMap::default())
109 pub fn single_file(file: FileId) -> SearchScope {
110 SearchScope::new(std::iter::once((file, None)).collect())
113 pub fn files(files: &[FileId]) -> SearchScope {
114 SearchScope::new(files.iter().map(|f| (*f, None)).collect())
117 pub fn intersection(&self, other: &SearchScope) -> SearchScope {
118 let (mut small, mut large) = (&self.entries, &other.entries);
119 if small.len() > large.len() {
120 mem::swap(&mut small, &mut large)
125 .filter_map(|(file_id, r1)| {
126 let r2 = large.get(file_id)?;
127 let r = intersect_ranges(*r1, *r2)?;
132 return SearchScope::new(res);
135 r1: Option<TextRange>,
136 r2: Option<TextRange>,
137 ) -> Option<Option<TextRange>> {
139 (None, r) | (r, None) => Some(r),
140 (Some(r1), Some(r2)) => {
141 let r = r1.intersect(r2)?;
149 impl IntoIterator for SearchScope {
150 type Item = (FileId, Option<TextRange>);
151 type IntoIter = std::collections::hash_map::IntoIter<FileId, Option<TextRange>>;
153 fn into_iter(self) -> Self::IntoIter {
154 self.entries.into_iter()
159 fn search_scope(&self, db: &RootDatabase) -> SearchScope {
160 let _p = profile::span("search_scope");
161 let module = match self.module(db) {
163 None => return SearchScope::empty(),
165 let module_src = module.definition_source(db);
166 let file_id = module_src.file_id.original_file(db);
168 if let Definition::Local(var) = self {
169 let range = match var.parent(db) {
170 DefWithBody::Function(f) => {
171 f.source(db).and_then(|src| Some(src.value.syntax().text_range()))
173 DefWithBody::Const(c) => {
174 c.source(db).and_then(|src| Some(src.value.syntax().text_range()))
176 DefWithBody::Static(s) => {
177 s.source(db).and_then(|src| Some(src.value.syntax().text_range()))
180 let mut res = FxHashMap::default();
181 res.insert(file_id, range);
182 return SearchScope::new(res);
185 if let Definition::GenericParam(hir::GenericParam::LifetimeParam(param)) = self {
186 let range = match param.parent(db) {
187 hir::GenericDef::Function(it) => {
188 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
190 hir::GenericDef::Adt(it) => match it {
191 hir::Adt::Struct(it) => {
192 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
194 hir::Adt::Union(it) => {
195 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
197 hir::Adt::Enum(it) => {
198 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
201 hir::GenericDef::Trait(it) => {
202 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
204 hir::GenericDef::TypeAlias(it) => {
205 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
207 hir::GenericDef::Impl(it) => {
208 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
210 hir::GenericDef::Variant(it) => {
211 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
213 hir::GenericDef::Const(it) => {
214 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
217 let mut res = FxHashMap::default();
218 res.insert(file_id, range);
219 return SearchScope::new(res);
222 let vis = self.visibility(db);
224 if let Some(Visibility::Module(module)) = vis.and_then(|it| it.into()) {
225 let module: Module = module.into();
226 let mut res = FxHashMap::default();
228 let mut to_visit = vec![module];
229 let mut is_first = true;
230 while let Some(module) = to_visit.pop() {
231 let src = module.definition_source(db);
232 let file_id = src.file_id.original_file(db);
234 ModuleSource::Module(m) => {
236 let range = Some(m.syntax().text_range());
237 res.insert(file_id, range);
239 // We have already added the enclosing file to the search scope,
243 ModuleSource::BlockExpr(b) => {
245 let range = Some(b.syntax().text_range());
246 res.insert(file_id, range);
248 // We have already added the enclosing file to the search scope,
252 ModuleSource::SourceFile(_) => {
253 res.insert(file_id, None);
257 to_visit.extend(module.children(db));
260 return SearchScope::new(res);
263 if let Some(Visibility::Public) = vis {
264 let source_root_id = db.file_source_root(file_id);
265 let source_root = db.source_root(source_root_id);
266 let mut res = source_root.iter().map(|id| (id, None)).collect::<FxHashMap<_, _>>();
268 let krate = module.krate();
269 for rev_dep in krate.reverse_dependencies(db) {
270 let root_file = rev_dep.root_file(db);
271 let source_root_id = db.file_source_root(root_file);
272 let source_root = db.source_root(source_root_id);
273 res.extend(source_root.iter().map(|id| (id, None)));
275 return SearchScope::new(res);
278 let mut res = FxHashMap::default();
279 let range = match module_src.value {
280 ModuleSource::Module(m) => Some(m.syntax().text_range()),
281 ModuleSource::BlockExpr(b) => Some(b.syntax().text_range()),
282 ModuleSource::SourceFile(_) => None,
284 res.insert(file_id, range);
285 SearchScope::new(res)
288 pub fn usages<'a>(&'a self, sema: &'a Semantics<RootDatabase>) -> FindUsages<'a> {
289 FindUsages { def: self, sema, scope: None }
293 pub struct FindUsages<'a> {
295 sema: &'a Semantics<'a, RootDatabase>,
296 scope: Option<SearchScope>,
299 impl<'a> FindUsages<'a> {
300 pub fn in_scope(self, scope: SearchScope) -> FindUsages<'a> {
301 self.set_scope(Some(scope))
303 pub fn set_scope(mut self, scope: Option<SearchScope>) -> FindUsages<'a> {
304 assert!(self.scope.is_none());
309 pub fn at_least_one(self) -> bool {
310 let mut found = false;
311 self.search(&mut |_, _| {
318 pub fn all(self) -> UsageSearchResult {
319 let mut res = UsageSearchResult::default();
320 self.search(&mut |file_id, reference| {
321 res.references.entry(file_id).or_default().push(reference);
327 fn search(self, sink: &mut dyn FnMut(FileId, FileReference) -> bool) {
328 let _p = profile::span("FindUsages:search");
329 let sema = self.sema;
332 let base = self.def.search_scope(sema.db);
335 Some(scope) => base.intersection(scope),
339 let name = match self.def.name(sema.db) {
340 Some(it) => it.to_string(),
344 let pat = name.as_str();
345 for (file_id, search_range) in search_scope {
346 let text = sema.db.file_text(file_id);
348 search_range.unwrap_or(TextRange::up_to(TextSize::of(text.as_str())));
350 let tree = Lazy::new(|| sema.parse(file_id).syntax().clone());
352 for (idx, _) in text.match_indices(pat) {
353 let offset: TextSize = idx.try_into().unwrap();
354 if !search_range.contains_inclusive(offset) {
358 if let Some(name_ref) = sema.find_node_at_offset_with_descend(&tree, offset) {
359 if self.found_name_ref(&name_ref, sink) {
362 } else if let Some(name) = sema.find_node_at_offset_with_descend(&tree, offset) {
363 if self.found_name(&name, sink) {
366 } else if let Some(lifetime) = sema.find_node_at_offset_with_descend(&tree, offset)
368 if self.found_lifetime(&lifetime, sink) {
378 lifetime: &ast::Lifetime,
379 sink: &mut dyn FnMut(FileId, FileReference) -> bool,
381 match NameRefClass::classify_lifetime(self.sema, lifetime) {
382 Some(NameRefClass::Definition(def)) if &def == self.def => {
383 let FileRange { file_id, range } = self.sema.original_range(lifetime.syntax());
384 let reference = FileReference {
386 name: NameLike::Lifetime(lifetime.clone()),
389 sink(file_id, reference)
391 _ => false, // not a usage
397 name_ref: &ast::NameRef,
398 sink: &mut dyn FnMut(FileId, FileReference) -> bool,
400 match NameRefClass::classify(self.sema, &name_ref) {
401 Some(NameRefClass::Definition(def)) if &def == self.def => {
402 let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
403 let reference = FileReference {
405 name: NameLike::NameRef(name_ref.clone()),
406 access: reference_access(&def, &name_ref),
408 sink(file_id, reference)
410 Some(NameRefClass::FieldShorthand { local_ref: local, field_ref: field }) => {
411 let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
412 let reference = match self.def {
413 Definition::Field(_) if &field == self.def => FileReference {
415 name: NameLike::NameRef(name_ref.clone()),
416 access: reference_access(&field, &name_ref),
418 Definition::Local(l) if &local == l => FileReference {
420 name: NameLike::NameRef(name_ref.clone()),
421 access: reference_access(&Definition::Local(local), &name_ref),
423 _ => return false, // not a usage
425 sink(file_id, reference)
427 _ => false, // not a usage
434 sink: &mut dyn FnMut(FileId, FileReference) -> bool,
436 match NameClass::classify(self.sema, name) {
437 Some(NameClass::PatFieldShorthand { local_def: _, field_ref }) => {
438 if !matches!(self.def, Definition::Field(_) if &field_ref == self.def) {
441 let FileRange { file_id, range } = self.sema.original_range(name.syntax());
442 let reference = FileReference {
444 name: NameLike::Name(name.clone()),
445 // FIXME: mutable patterns should have `Write` access
446 access: Some(ReferenceAccess::Read),
448 sink(file_id, reference)
450 _ => false, // not a usage
455 fn reference_access(def: &Definition, name_ref: &ast::NameRef) -> Option<ReferenceAccess> {
456 // Only Locals and Fields have accesses for now.
457 if !matches!(def, Definition::Local(_) | Definition::Field(_)) {
461 let mode = name_ref.syntax().ancestors().find_map(|node| {
464 ast::BinExpr(expr) => {
465 if expr.op_kind()?.is_assignment() {
466 // If the variable or field ends on the LHS's end then it's a Write (covers fields and locals).
467 // FIXME: This is not terribly accurate.
468 if let Some(lhs) = expr.lhs() {
469 if lhs.syntax().text_range().end() == name_ref.syntax().text_range().end() {
470 return Some(ReferenceAccess::Write);
474 Some(ReferenceAccess::Read)
481 // Default Locals and Fields to read
482 mode.or(Some(ReferenceAccess::Read))