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)]
56 pub struct FileReference {
58 pub name: ast::NameLike,
59 pub access: Option<ReferenceAccess>,
62 #[derive(Debug, Copy, Clone, PartialEq)]
63 pub enum ReferenceAccess {
68 /// Generally, `search_scope` returns files that might contain references for the element.
69 /// For `pub(crate)` things it's a crate, for `pub` things it's a crate and dependant crates.
70 /// In some cases, the location of the references is known to within a `TextRange`,
71 /// e.g. for things like local variables.
72 pub struct SearchScope {
73 entries: FxHashMap<FileId, Option<TextRange>>,
77 fn new(entries: FxHashMap<FileId, Option<TextRange>>) -> SearchScope {
78 SearchScope { entries }
81 pub fn empty() -> SearchScope {
82 SearchScope::new(FxHashMap::default())
85 pub fn single_file(file: FileId) -> SearchScope {
86 SearchScope::new(std::iter::once((file, None)).collect())
89 pub fn files(files: &[FileId]) -> SearchScope {
90 SearchScope::new(files.iter().map(|f| (*f, None)).collect())
93 pub fn intersection(&self, other: &SearchScope) -> SearchScope {
94 let (mut small, mut large) = (&self.entries, &other.entries);
95 if small.len() > large.len() {
96 mem::swap(&mut small, &mut large)
101 .filter_map(|(file_id, r1)| {
102 let r2 = large.get(file_id)?;
103 let r = intersect_ranges(*r1, *r2)?;
108 return SearchScope::new(res);
111 r1: Option<TextRange>,
112 r2: Option<TextRange>,
113 ) -> Option<Option<TextRange>> {
115 (None, r) | (r, None) => Some(r),
116 (Some(r1), Some(r2)) => {
117 let r = r1.intersect(r2)?;
125 impl IntoIterator for SearchScope {
126 type Item = (FileId, Option<TextRange>);
127 type IntoIter = std::collections::hash_map::IntoIter<FileId, Option<TextRange>>;
129 fn into_iter(self) -> Self::IntoIter {
130 self.entries.into_iter()
135 fn search_scope(&self, db: &RootDatabase) -> SearchScope {
136 let _p = profile::span("search_scope");
137 let module = match self.module(db) {
139 None => return SearchScope::empty(),
141 let module_src = module.definition_source(db);
142 let file_id = module_src.file_id.original_file(db);
144 if let Definition::Local(var) = self {
145 let range = match var.parent(db) {
146 DefWithBody::Function(f) => {
147 f.source(db).and_then(|src| Some(src.value.syntax().text_range()))
149 DefWithBody::Const(c) => {
150 c.source(db).and_then(|src| Some(src.value.syntax().text_range()))
152 DefWithBody::Static(s) => {
153 s.source(db).and_then(|src| Some(src.value.syntax().text_range()))
156 let mut res = FxHashMap::default();
157 res.insert(file_id, range);
158 return SearchScope::new(res);
161 if let Definition::GenericParam(hir::GenericParam::LifetimeParam(param)) = self {
162 let range = match param.parent(db) {
163 hir::GenericDef::Function(it) => {
164 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
166 hir::GenericDef::Adt(it) => match it {
167 hir::Adt::Struct(it) => {
168 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
170 hir::Adt::Union(it) => {
171 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
173 hir::Adt::Enum(it) => {
174 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
177 hir::GenericDef::Trait(it) => {
178 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
180 hir::GenericDef::TypeAlias(it) => {
181 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
183 hir::GenericDef::Impl(it) => {
184 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
186 hir::GenericDef::Variant(it) => {
187 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
189 hir::GenericDef::Const(it) => {
190 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
193 let mut res = FxHashMap::default();
194 res.insert(file_id, range);
195 return SearchScope::new(res);
198 let vis = self.visibility(db);
200 if let Some(Visibility::Module(module)) = vis.and_then(|it| it.into()) {
201 let module: Module = module.into();
202 let mut res = FxHashMap::default();
204 let mut to_visit = vec![module];
205 let mut is_first = true;
206 while let Some(module) = to_visit.pop() {
207 let src = module.definition_source(db);
208 let file_id = src.file_id.original_file(db);
210 ModuleSource::Module(m) => {
212 let range = Some(m.syntax().text_range());
213 res.insert(file_id, range);
215 // We have already added the enclosing file to the search scope,
219 ModuleSource::BlockExpr(b) => {
221 let range = Some(b.syntax().text_range());
222 res.insert(file_id, range);
224 // We have already added the enclosing file to the search scope,
228 ModuleSource::SourceFile(_) => {
229 res.insert(file_id, None);
233 to_visit.extend(module.children(db));
236 return SearchScope::new(res);
239 if let Some(Visibility::Public) = vis {
240 let source_root_id = db.file_source_root(file_id);
241 let source_root = db.source_root(source_root_id);
242 let mut res = source_root.iter().map(|id| (id, None)).collect::<FxHashMap<_, _>>();
244 let krate = module.krate();
245 for rev_dep in krate.reverse_dependencies(db) {
246 let root_file = rev_dep.root_file(db);
247 let source_root_id = db.file_source_root(root_file);
248 let source_root = db.source_root(source_root_id);
249 res.extend(source_root.iter().map(|id| (id, None)));
251 return SearchScope::new(res);
254 let mut res = FxHashMap::default();
255 let range = match module_src.value {
256 ModuleSource::Module(m) => Some(m.syntax().text_range()),
257 ModuleSource::BlockExpr(b) => Some(b.syntax().text_range()),
258 ModuleSource::SourceFile(_) => None,
260 res.insert(file_id, range);
261 SearchScope::new(res)
264 pub fn usages<'a>(&'a self, sema: &'a Semantics<RootDatabase>) -> FindUsages<'a> {
265 FindUsages { def: self, sema, scope: None }
269 pub struct FindUsages<'a> {
271 sema: &'a Semantics<'a, RootDatabase>,
272 scope: Option<SearchScope>,
275 impl<'a> FindUsages<'a> {
276 pub fn in_scope(self, scope: SearchScope) -> FindUsages<'a> {
277 self.set_scope(Some(scope))
280 pub fn set_scope(mut self, scope: Option<SearchScope>) -> FindUsages<'a> {
281 assert!(self.scope.is_none());
286 pub fn at_least_one(self) -> bool {
287 let mut found = false;
288 self.search(&mut |_, _| {
295 pub fn all(self) -> UsageSearchResult {
296 let mut res = UsageSearchResult::default();
297 self.search(&mut |file_id, reference| {
298 res.references.entry(file_id).or_default().push(reference);
304 fn search(self, sink: &mut dyn FnMut(FileId, FileReference) -> bool) {
305 let _p = profile::span("FindUsages:search");
306 let sema = self.sema;
309 let base = self.def.search_scope(sema.db);
312 Some(scope) => base.intersection(scope),
316 let name = match self.def.name(sema.db) {
317 Some(it) => it.to_string(),
321 let pat = name.as_str();
322 for (file_id, search_range) in search_scope {
323 let text = sema.db.file_text(file_id);
325 search_range.unwrap_or_else(|| TextRange::up_to(TextSize::of(text.as_str())));
327 let tree = Lazy::new(|| sema.parse(file_id).syntax().clone());
329 for (idx, _) in text.match_indices(pat) {
330 let offset: TextSize = idx.try_into().unwrap();
331 if !search_range.contains_inclusive(offset) {
335 if let Some(name) = sema.find_node_at_offset_with_descend(&tree, offset) {
337 ast::NameLike::NameRef(name_ref) => {
338 if self.found_name_ref(&name_ref, sink) {
342 ast::NameLike::Name(name) => {
343 if self.found_name(&name, sink) {
347 ast::NameLike::Lifetime(lifetime) => {
348 if self.found_lifetime(&lifetime, sink) {
360 lifetime: &ast::Lifetime,
361 sink: &mut dyn FnMut(FileId, FileReference) -> bool,
363 match NameRefClass::classify_lifetime(self.sema, lifetime) {
364 Some(NameRefClass::Definition(def)) if &def == self.def => {
365 let FileRange { file_id, range } = self.sema.original_range(lifetime.syntax());
366 let reference = FileReference {
368 name: ast::NameLike::Lifetime(lifetime.clone()),
371 sink(file_id, reference)
373 _ => false, // not a usage
379 name_ref: &ast::NameRef,
380 sink: &mut dyn FnMut(FileId, FileReference) -> bool,
382 match NameRefClass::classify(self.sema, &name_ref) {
383 Some(NameRefClass::Definition(def)) if &def == self.def => {
384 let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
385 let reference = FileReference {
387 name: ast::NameLike::NameRef(name_ref.clone()),
388 access: reference_access(&def, &name_ref),
390 sink(file_id, reference)
392 Some(NameRefClass::FieldShorthand { local_ref: local, field_ref: field }) => {
393 let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
394 let reference = match self.def {
395 Definition::Field(_) if &field == self.def => FileReference {
397 name: ast::NameLike::NameRef(name_ref.clone()),
398 access: reference_access(&field, &name_ref),
400 Definition::Local(l) if &local == l => FileReference {
402 name: ast::NameLike::NameRef(name_ref.clone()),
403 access: reference_access(&Definition::Local(local), &name_ref),
405 _ => return false, // not a usage
407 sink(file_id, reference)
409 _ => false, // not a usage
416 sink: &mut dyn FnMut(FileId, FileReference) -> bool,
418 match NameClass::classify(self.sema, name) {
419 Some(NameClass::PatFieldShorthand { local_def: _, field_ref })
421 self.def, Definition::Field(_) if &field_ref == self.def
424 let FileRange { file_id, range } = self.sema.original_range(name.syntax());
425 let reference = FileReference {
427 name: ast::NameLike::Name(name.clone()),
428 // FIXME: mutable patterns should have `Write` access
429 access: Some(ReferenceAccess::Read),
431 sink(file_id, reference)
433 Some(NameClass::ConstReference(def)) if *self.def == def => {
434 let FileRange { file_id, range } = self.sema.original_range(name.syntax());
436 FileReference { range, name: ast::NameLike::Name(name.clone()), access: None };
437 sink(file_id, reference)
439 _ => false, // not a usage
444 fn reference_access(def: &Definition, name_ref: &ast::NameRef) -> Option<ReferenceAccess> {
445 // Only Locals and Fields have accesses for now.
446 if !matches!(def, Definition::Local(_) | Definition::Field(_)) {
450 let mode = name_ref.syntax().ancestors().find_map(|node| {
453 ast::BinExpr(expr) => {
454 if expr.op_kind()?.is_assignment() {
455 // If the variable or field ends on the LHS's end then it's a Write (covers fields and locals).
456 // FIXME: This is not terribly accurate.
457 if let Some(lhs) = expr.lhs() {
458 if lhs.syntax().text_range().end() == name_ref.syntax().text_range().end() {
459 return Some(ReferenceAccess::Write);
463 Some(ReferenceAccess::Read)
470 // Default Locals and Fields to read
471 mode.or(Some(ReferenceAccess::Read))