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 file_part(file: FileId, range: TextRange) -> SearchScope {
90 SearchScope::new(std::iter::once((file, Some(range))).collect())
93 pub fn files(files: &[FileId]) -> SearchScope {
94 SearchScope::new(files.iter().map(|f| (*f, None)).collect())
97 pub fn intersection(&self, other: &SearchScope) -> SearchScope {
98 let (mut small, mut large) = (&self.entries, &other.entries);
99 if small.len() > large.len() {
100 mem::swap(&mut small, &mut large)
105 .filter_map(|(file_id, r1)| {
106 let r2 = large.get(file_id)?;
107 let r = intersect_ranges(*r1, *r2)?;
112 return SearchScope::new(res);
115 r1: Option<TextRange>,
116 r2: Option<TextRange>,
117 ) -> Option<Option<TextRange>> {
119 (None, r) | (r, None) => Some(r),
120 (Some(r1), Some(r2)) => {
121 let r = r1.intersect(r2)?;
129 impl IntoIterator for SearchScope {
130 type Item = (FileId, Option<TextRange>);
131 type IntoIter = std::collections::hash_map::IntoIter<FileId, Option<TextRange>>;
133 fn into_iter(self) -> Self::IntoIter {
134 self.entries.into_iter()
139 fn search_scope(&self, db: &RootDatabase) -> SearchScope {
140 let _p = profile::span("search_scope");
141 let module = match self.module(db) {
143 None => return SearchScope::empty(),
145 let module_src = module.definition_source(db);
146 let file_id = module_src.file_id.original_file(db);
148 if let Definition::Local(var) = self {
149 let range = match var.parent(db) {
150 DefWithBody::Function(f) => {
151 f.source(db).and_then(|src| Some(src.value.syntax().text_range()))
153 DefWithBody::Const(c) => {
154 c.source(db).and_then(|src| Some(src.value.syntax().text_range()))
156 DefWithBody::Static(s) => {
157 s.source(db).and_then(|src| Some(src.value.syntax().text_range()))
160 let mut res = FxHashMap::default();
161 res.insert(file_id, range);
162 return SearchScope::new(res);
165 if let Definition::GenericParam(hir::GenericParam::LifetimeParam(param)) = self {
166 let range = match param.parent(db) {
167 hir::GenericDef::Function(it) => {
168 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
170 hir::GenericDef::Adt(it) => match it {
171 hir::Adt::Struct(it) => {
172 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
174 hir::Adt::Union(it) => {
175 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
177 hir::Adt::Enum(it) => {
178 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
181 hir::GenericDef::Trait(it) => {
182 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
184 hir::GenericDef::TypeAlias(it) => {
185 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
187 hir::GenericDef::Impl(it) => {
188 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
190 hir::GenericDef::Variant(it) => {
191 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
193 hir::GenericDef::Const(it) => {
194 it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
197 let mut res = FxHashMap::default();
198 res.insert(file_id, range);
199 return SearchScope::new(res);
202 let vis = self.visibility(db);
204 if let Some(Visibility::Module(module)) = vis.and_then(|it| it.into()) {
205 let module: Module = module.into();
206 let mut res = FxHashMap::default();
208 let mut to_visit = vec![module];
209 let mut is_first = true;
210 while let Some(module) = to_visit.pop() {
211 let src = module.definition_source(db);
212 let file_id = src.file_id.original_file(db);
214 ModuleSource::Module(m) => {
216 let range = Some(m.syntax().text_range());
217 res.insert(file_id, range);
219 // We have already added the enclosing file to the search scope,
223 ModuleSource::BlockExpr(b) => {
225 let range = Some(b.syntax().text_range());
226 res.insert(file_id, range);
228 // We have already added the enclosing file to the search scope,
232 ModuleSource::SourceFile(_) => {
233 res.insert(file_id, None);
237 to_visit.extend(module.children(db));
240 return SearchScope::new(res);
243 if let Some(Visibility::Public) = vis {
244 let source_root_id = db.file_source_root(file_id);
245 let source_root = db.source_root(source_root_id);
246 let mut res = source_root.iter().map(|id| (id, None)).collect::<FxHashMap<_, _>>();
248 let krate = module.krate();
249 for rev_dep in krate.reverse_dependencies(db) {
250 let root_file = rev_dep.root_file(db);
251 let source_root_id = db.file_source_root(root_file);
252 let source_root = db.source_root(source_root_id);
253 res.extend(source_root.iter().map(|id| (id, None)));
255 return SearchScope::new(res);
258 let mut res = FxHashMap::default();
259 let range = match module_src.value {
260 ModuleSource::Module(m) => Some(m.syntax().text_range()),
261 ModuleSource::BlockExpr(b) => Some(b.syntax().text_range()),
262 ModuleSource::SourceFile(_) => None,
264 res.insert(file_id, range);
265 SearchScope::new(res)
268 pub fn usages<'a>(&'a self, sema: &'a Semantics<RootDatabase>) -> FindUsages<'a> {
269 FindUsages { def: self, sema, scope: None }
273 pub struct FindUsages<'a> {
275 sema: &'a Semantics<'a, RootDatabase>,
276 scope: Option<SearchScope>,
279 impl<'a> FindUsages<'a> {
280 pub fn in_scope(self, scope: SearchScope) -> FindUsages<'a> {
281 self.set_scope(Some(scope))
284 pub fn set_scope(mut self, scope: Option<SearchScope>) -> FindUsages<'a> {
285 assert!(self.scope.is_none());
290 pub fn at_least_one(self) -> bool {
291 let mut found = false;
292 self.search(&mut |_, _| {
299 pub fn all(self) -> UsageSearchResult {
300 let mut res = UsageSearchResult::default();
301 self.search(&mut |file_id, reference| {
302 res.references.entry(file_id).or_default().push(reference);
308 fn search(self, sink: &mut dyn FnMut(FileId, FileReference) -> bool) {
309 let _p = profile::span("FindUsages:search");
310 let sema = self.sema;
313 let base = self.def.search_scope(sema.db);
316 Some(scope) => base.intersection(scope),
320 let name = match self.def.name(sema.db) {
321 Some(it) => it.to_string(),
325 let pat = name.as_str();
326 for (file_id, search_range) in search_scope {
327 let text = sema.db.file_text(file_id);
329 search_range.unwrap_or_else(|| TextRange::up_to(TextSize::of(text.as_str())));
331 let tree = Lazy::new(|| sema.parse(file_id).syntax().clone());
333 for (idx, _) in text.match_indices(pat) {
334 let offset: TextSize = idx.try_into().unwrap();
335 if !search_range.contains_inclusive(offset) {
339 if let Some(name) = sema.find_node_at_offset_with_descend(&tree, offset) {
341 ast::NameLike::NameRef(name_ref) => {
342 if self.found_name_ref(&name_ref, sink) {
346 ast::NameLike::Name(name) => {
347 if self.found_name(&name, sink) {
351 ast::NameLike::Lifetime(lifetime) => {
352 if self.found_lifetime(&lifetime, sink) {
364 lifetime: &ast::Lifetime,
365 sink: &mut dyn FnMut(FileId, FileReference) -> bool,
367 match NameRefClass::classify_lifetime(self.sema, lifetime) {
368 Some(NameRefClass::Definition(def)) if &def == self.def => {
369 let FileRange { file_id, range } = self.sema.original_range(lifetime.syntax());
370 let reference = FileReference {
372 name: ast::NameLike::Lifetime(lifetime.clone()),
375 sink(file_id, reference)
377 _ => false, // not a usage
383 name_ref: &ast::NameRef,
384 sink: &mut dyn FnMut(FileId, FileReference) -> bool,
386 match NameRefClass::classify(self.sema, &name_ref) {
387 Some(NameRefClass::Definition(def)) if &def == self.def => {
388 let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
389 let reference = FileReference {
391 name: ast::NameLike::NameRef(name_ref.clone()),
392 access: reference_access(&def, &name_ref),
394 sink(file_id, reference)
396 Some(NameRefClass::FieldShorthand { local_ref: local, field_ref: field }) => {
397 let FileRange { file_id, range } = self.sema.original_range(name_ref.syntax());
398 let reference = match self.def {
399 Definition::Field(_) if &field == self.def => FileReference {
401 name: ast::NameLike::NameRef(name_ref.clone()),
402 access: reference_access(&field, &name_ref),
404 Definition::Local(l) if &local == l => FileReference {
406 name: ast::NameLike::NameRef(name_ref.clone()),
407 access: reference_access(&Definition::Local(local), &name_ref),
409 _ => return false, // not a usage
411 sink(file_id, reference)
413 _ => false, // not a usage
420 sink: &mut dyn FnMut(FileId, FileReference) -> bool,
422 match NameClass::classify(self.sema, name) {
423 Some(NameClass::PatFieldShorthand { local_def: _, field_ref })
425 self.def, Definition::Field(_) if &field_ref == self.def
428 let FileRange { file_id, range } = self.sema.original_range(name.syntax());
429 let reference = FileReference {
431 name: ast::NameLike::Name(name.clone()),
432 // FIXME: mutable patterns should have `Write` access
433 access: Some(ReferenceAccess::Read),
435 sink(file_id, reference)
437 Some(NameClass::ConstReference(def)) if *self.def == def => {
438 let FileRange { file_id, range } = self.sema.original_range(name.syntax());
440 FileReference { range, name: ast::NameLike::Name(name.clone()), access: None };
441 sink(file_id, reference)
443 _ => false, // not a usage
448 fn reference_access(def: &Definition, name_ref: &ast::NameRef) -> Option<ReferenceAccess> {
449 // Only Locals and Fields have accesses for now.
450 if !matches!(def, Definition::Local(_) | Definition::Field(_)) {
454 let mode = name_ref.syntax().ancestors().find_map(|node| {
457 ast::BinExpr(expr) => {
458 if expr.op_kind()?.is_assignment() {
459 // If the variable or field ends on the LHS's end then it's a Write (covers fields and locals).
460 // FIXME: This is not terribly accurate.
461 if let Some(lhs) = expr.lhs() {
462 if lhs.syntax().text_range().end() == name_ref.syntax().text_range().end() {
463 return Some(ReferenceAccess::Write);
467 Some(ReferenceAccess::Read)
474 // Default Locals and Fields to read
475 mode.or(Some(ReferenceAccess::Read))