]> git.lizzy.rs Git - rust.git/blob - crates/ide_db/src/search.rs
ddcfbd3f3ff3d7a5ac607f6d6fac827e3f5710c6
[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};
8
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};
14
15 use crate::defs::NameClass;
16 use crate::{
17     defs::{Definition, NameRefClass},
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, &Vec<FileReference>)> + '_ {
36         self.references.iter()
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 access: Option<ReferenceAccess>,
60 }
61
62 #[derive(Debug, Copy, Clone, PartialEq)]
63 pub enum ReferenceAccess {
64     Read,
65     Write,
66 }
67
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>>,
74 }
75
76 impl SearchScope {
77     fn new(entries: FxHashMap<FileId, Option<TextRange>>) -> SearchScope {
78         SearchScope { entries }
79     }
80
81     pub fn empty() -> SearchScope {
82         SearchScope::new(FxHashMap::default())
83     }
84
85     pub fn single_file(file: FileId) -> SearchScope {
86         SearchScope::new(std::iter::once((file, None)).collect())
87     }
88
89     pub fn files(files: &[FileId]) -> SearchScope {
90         SearchScope::new(files.iter().map(|f| (*f, None)).collect())
91     }
92
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)
97         }
98
99         let res = small
100             .iter()
101             .filter_map(|(file_id, r1)| {
102                 let r2 = large.get(file_id)?;
103                 let r = intersect_ranges(*r1, *r2)?;
104                 Some((*file_id, r))
105             })
106             .collect();
107
108         return SearchScope::new(res);
109
110         fn intersect_ranges(
111             r1: Option<TextRange>,
112             r2: Option<TextRange>,
113         ) -> Option<Option<TextRange>> {
114             match (r1, r2) {
115                 (None, r) | (r, None) => Some(r),
116                 (Some(r1), Some(r2)) => {
117                     let r = r1.intersect(r2)?;
118                     Some(Some(r))
119                 }
120             }
121         }
122     }
123 }
124
125 impl IntoIterator for SearchScope {
126     type Item = (FileId, Option<TextRange>);
127     type IntoIter = std::collections::hash_map::IntoIter<FileId, Option<TextRange>>;
128
129     fn into_iter(self) -> Self::IntoIter {
130         self.entries.into_iter()
131     }
132 }
133
134 impl Definition {
135     fn search_scope(&self, db: &RootDatabase) -> SearchScope {
136         let _p = profile::span("search_scope");
137         let module = match self.module(db) {
138             Some(it) => it,
139             None => return SearchScope::empty(),
140         };
141         let module_src = module.definition_source(db);
142         let file_id = module_src.file_id.original_file(db);
143
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()))
148                 }
149                 DefWithBody::Const(c) => {
150                     c.source(db).and_then(|src| Some(src.value.syntax().text_range()))
151                 }
152                 DefWithBody::Static(s) => {
153                     s.source(db).and_then(|src| Some(src.value.syntax().text_range()))
154                 }
155             };
156             let mut res = FxHashMap::default();
157             res.insert(file_id, range);
158             return SearchScope::new(res);
159         }
160
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()))
165                 }
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()))
169                     }
170                     hir::Adt::Union(it) => {
171                         it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
172                     }
173                     hir::Adt::Enum(it) => {
174                         it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
175                     }
176                 },
177                 hir::GenericDef::Trait(it) => {
178                     it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
179                 }
180                 hir::GenericDef::TypeAlias(it) => {
181                     it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
182                 }
183                 hir::GenericDef::Impl(it) => {
184                     it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
185                 }
186                 hir::GenericDef::Variant(it) => {
187                     it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
188                 }
189                 hir::GenericDef::Const(it) => {
190                     it.source(db).and_then(|src| Some(src.value.syntax().text_range()))
191                 }
192             };
193             let mut res = FxHashMap::default();
194             res.insert(file_id, range);
195             return SearchScope::new(res);
196         }
197
198         let vis = self.visibility(db);
199
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();
203
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);
209                 match src.value {
210                     ModuleSource::Module(m) => {
211                         if is_first {
212                             let range = Some(m.syntax().text_range());
213                             res.insert(file_id, range);
214                         } else {
215                             // We have already added the enclosing file to the search scope,
216                             // so do nothing.
217                         }
218                     }
219                     ModuleSource::BlockExpr(b) => {
220                         if is_first {
221                             let range = Some(b.syntax().text_range());
222                             res.insert(file_id, range);
223                         } else {
224                             // We have already added the enclosing file to the search scope,
225                             // so do nothing.
226                         }
227                     }
228                     ModuleSource::SourceFile(_) => {
229                         res.insert(file_id, None);
230                     }
231                 };
232                 is_first = false;
233                 to_visit.extend(module.children(db));
234             }
235
236             return SearchScope::new(res);
237         }
238
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<_, _>>();
243
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)));
250             }
251             return SearchScope::new(res);
252         }
253
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,
259         };
260         res.insert(file_id, range);
261         SearchScope::new(res)
262     }
263
264     pub fn usages<'a>(&'a self, sema: &'a Semantics<RootDatabase>) -> FindUsages<'a> {
265         FindUsages { def: self, sema, scope: None }
266     }
267 }
268
269 pub struct FindUsages<'a> {
270     def: &'a Definition,
271     sema: &'a Semantics<'a, RootDatabase>,
272     scope: Option<SearchScope>,
273 }
274
275 impl<'a> FindUsages<'a> {
276     pub fn in_scope(self, scope: SearchScope) -> FindUsages<'a> {
277         self.set_scope(Some(scope))
278     }
279
280     pub fn set_scope(mut self, scope: Option<SearchScope>) -> FindUsages<'a> {
281         assert!(self.scope.is_none());
282         self.scope = scope;
283         self
284     }
285
286     pub fn at_least_one(self) -> bool {
287         let mut found = false;
288         self.search(&mut |_, _| {
289             found = true;
290             true
291         });
292         found
293     }
294
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);
299             false
300         });
301         res
302     }
303
304     fn search(self, sink: &mut dyn FnMut(FileId, FileReference) -> bool) {
305         let _p = profile::span("FindUsages:search");
306         let sema = self.sema;
307
308         let search_scope = {
309             let base = self.def.search_scope(sema.db);
310             match &self.scope {
311                 None => base,
312                 Some(scope) => base.intersection(scope),
313             }
314         };
315
316         let name = match self.def.name(sema.db) {
317             Some(it) => it.to_string(),
318             None => return,
319         };
320
321         let pat = name.as_str();
322         for (file_id, search_range) in search_scope {
323             let text = sema.db.file_text(file_id);
324             let search_range =
325                 search_range.unwrap_or_else(|| TextRange::up_to(TextSize::of(text.as_str())));
326
327             let tree = Lazy::new(|| sema.parse(file_id).syntax().clone());
328
329             for (idx, _) in text.match_indices(pat) {
330                 let offset: TextSize = idx.try_into().unwrap();
331                 if !search_range.contains_inclusive(offset) {
332                     continue;
333                 }
334
335                 if let Some(name) = sema.find_node_at_offset_with_descend(&tree, offset) {
336                     match name {
337                         ast::NameLike::NameRef(name_ref) => {
338                             if self.found_name_ref(&name_ref, sink) {
339                                 return;
340                             }
341                         }
342                         ast::NameLike::Name(name) => {
343                             if self.found_name(&name, sink) {
344                                 return;
345                             }
346                         }
347                         ast::NameLike::Lifetime(lifetime) => {
348                             if self.found_lifetime(&lifetime, sink) {
349                                 return;
350                             }
351                         }
352                     }
353                 }
354             }
355         }
356     }
357
358     fn found_lifetime(
359         &self,
360         lifetime: &ast::Lifetime,
361         sink: &mut dyn FnMut(FileId, FileReference) -> bool,
362     ) -> 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 {
367                     range,
368                     name: ast::NameLike::Lifetime(lifetime.clone()),
369                     access: None,
370                 };
371                 sink(file_id, reference)
372             }
373             _ => false, // not a usage
374         }
375     }
376
377     fn found_name_ref(
378         &self,
379         name_ref: &ast::NameRef,
380         sink: &mut dyn FnMut(FileId, FileReference) -> bool,
381     ) -> 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 {
386                     range,
387                     name: ast::NameLike::NameRef(name_ref.clone()),
388                     access: reference_access(&def, &name_ref),
389                 };
390                 sink(file_id, reference)
391             }
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 {
396                         range,
397                         name: ast::NameLike::NameRef(name_ref.clone()),
398                         access: reference_access(&field, &name_ref),
399                     },
400                     Definition::Local(l) if &local == l => FileReference {
401                         range,
402                         name: ast::NameLike::NameRef(name_ref.clone()),
403                         access: reference_access(&Definition::Local(local), &name_ref),
404                     },
405                     _ => return false, // not a usage
406                 };
407                 sink(file_id, reference)
408             }
409             _ => false, // not a usage
410         }
411     }
412
413     fn found_name(
414         &self,
415         name: &ast::Name,
416         sink: &mut dyn FnMut(FileId, FileReference) -> bool,
417     ) -> bool {
418         match NameClass::classify(self.sema, name) {
419             Some(NameClass::PatFieldShorthand { local_def: _, field_ref })
420                 if matches!(
421                     self.def, Definition::Field(_) if &field_ref == self.def
422                 ) =>
423             {
424                 let FileRange { file_id, range } = self.sema.original_range(name.syntax());
425                 let reference = FileReference {
426                     range,
427                     name: ast::NameLike::Name(name.clone()),
428                     // FIXME: mutable patterns should have `Write` access
429                     access: Some(ReferenceAccess::Read),
430                 };
431                 sink(file_id, reference)
432             }
433             Some(NameClass::ConstReference(def)) if *self.def == def => {
434                 let FileRange { file_id, range } = self.sema.original_range(name.syntax());
435                 let reference =
436                     FileReference { range, name: ast::NameLike::Name(name.clone()), access: None };
437                 sink(file_id, reference)
438             }
439             _ => false, // not a usage
440         }
441     }
442 }
443
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(_)) {
447         return None;
448     }
449
450     let mode = name_ref.syntax().ancestors().find_map(|node| {
451         match_ast! {
452             match (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);
460                             }
461                         }
462                     }
463                     Some(ReferenceAccess::Read)
464                 },
465                 _ => None
466             }
467         }
468     });
469
470     // Default Locals and Fields to read
471     mode.or(Some(ReferenceAccess::Read))
472 }