]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/ide/src/static_index.rs
:arrow_up: rust-analyzer
[rust.git] / src / tools / rust-analyzer / crates / ide / src / static_index.rs
1 //! This module provides `StaticIndex` which is used for powering
2 //! read-only code browsers and emitting LSIF
3
4 use std::collections::HashMap;
5
6 use hir::{db::HirDatabase, Crate, Module, Semantics};
7 use ide_db::{
8     base_db::{FileId, FileRange, SourceDatabaseExt},
9     defs::{Definition, IdentClass},
10     FxHashSet, RootDatabase,
11 };
12 use syntax::{AstNode, SyntaxKind::*, SyntaxToken, TextRange, T};
13
14 use crate::{
15     hover::hover_for_definition,
16     moniker::{crate_for_file, def_to_moniker, MonikerResult},
17     Analysis, Fold, HoverConfig, HoverDocFormat, HoverResult, InlayHint, InlayHintsConfig,
18     TryToNav,
19 };
20
21 /// A static representation of fully analyzed source code.
22 ///
23 /// The intended use-case is powering read-only code browsers and emitting LSIF
24 #[derive(Debug)]
25 pub struct StaticIndex<'a> {
26     pub files: Vec<StaticIndexedFile>,
27     pub tokens: TokenStore,
28     analysis: &'a Analysis,
29     db: &'a RootDatabase,
30     def_map: HashMap<Definition, TokenId>,
31 }
32
33 #[derive(Debug)]
34 pub struct ReferenceData {
35     pub range: FileRange,
36     pub is_definition: bool,
37 }
38
39 #[derive(Debug)]
40 pub struct TokenStaticData {
41     pub hover: Option<HoverResult>,
42     pub definition: Option<FileRange>,
43     pub references: Vec<ReferenceData>,
44     pub moniker: Option<MonikerResult>,
45 }
46
47 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48 pub struct TokenId(usize);
49
50 impl TokenId {
51     pub fn raw(self) -> usize {
52         self.0
53     }
54 }
55
56 #[derive(Default, Debug)]
57 pub struct TokenStore(Vec<TokenStaticData>);
58
59 impl TokenStore {
60     pub fn insert(&mut self, data: TokenStaticData) -> TokenId {
61         let id = TokenId(self.0.len());
62         self.0.push(data);
63         id
64     }
65
66     pub fn get_mut(&mut self, id: TokenId) -> Option<&mut TokenStaticData> {
67         self.0.get_mut(id.0)
68     }
69
70     pub fn get(&self, id: TokenId) -> Option<&TokenStaticData> {
71         self.0.get(id.0)
72     }
73
74     pub fn iter(self) -> impl Iterator<Item = (TokenId, TokenStaticData)> {
75         self.0.into_iter().enumerate().map(|(i, x)| (TokenId(i), x))
76     }
77 }
78
79 #[derive(Debug)]
80 pub struct StaticIndexedFile {
81     pub file_id: FileId,
82     pub folds: Vec<Fold>,
83     pub inlay_hints: Vec<InlayHint>,
84     pub tokens: Vec<(TextRange, TokenId)>,
85 }
86
87 fn all_modules(db: &dyn HirDatabase) -> Vec<Module> {
88     let mut worklist: Vec<_> =
89         Crate::all(db).into_iter().map(|krate| krate.root_module(db)).collect();
90     let mut modules = Vec::new();
91
92     while let Some(module) = worklist.pop() {
93         modules.push(module);
94         worklist.extend(module.children(db));
95     }
96
97     modules
98 }
99
100 impl StaticIndex<'_> {
101     fn add_file(&mut self, file_id: FileId) {
102         let current_crate = crate_for_file(self.db, file_id);
103         let folds = self.analysis.folding_ranges(file_id).unwrap();
104         let inlay_hints = self
105             .analysis
106             .inlay_hints(
107                 &InlayHintsConfig {
108                     render_colons: true,
109                     type_hints: true,
110                     parameter_hints: true,
111                     chaining_hints: true,
112                     closure_return_type_hints: crate::ClosureReturnTypeHints::WithBlock,
113                     lifetime_elision_hints: crate::LifetimeElisionHints::Never,
114                     reborrow_hints: crate::ReborrowHints::Never,
115                     hide_named_constructor_hints: false,
116                     hide_closure_initialization_hints: false,
117                     param_names_for_lifetime_elision_hints: false,
118                     binding_mode_hints: false,
119                     max_length: Some(25),
120                     closing_brace_hints_min_lines: Some(25),
121                 },
122                 file_id,
123                 None,
124             )
125             .unwrap();
126         // hovers
127         let sema = hir::Semantics::new(self.db);
128         let tokens_or_nodes = sema.parse(file_id).syntax().clone();
129         let tokens = tokens_or_nodes.descendants_with_tokens().filter_map(|x| match x {
130             syntax::NodeOrToken::Node(_) => None,
131             syntax::NodeOrToken::Token(x) => Some(x),
132         });
133         let hover_config = HoverConfig {
134             links_in_hover: true,
135             documentation: Some(HoverDocFormat::Markdown),
136             keywords: true,
137         };
138         let tokens = tokens.filter(|token| {
139             matches!(
140                 token.kind(),
141                 IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] | T![Self]
142             )
143         });
144         let mut result = StaticIndexedFile { file_id, inlay_hints, folds, tokens: vec![] };
145         for token in tokens {
146             let range = token.text_range();
147             let node = token.parent().unwrap();
148             let def = match get_definition(&sema, token.clone()) {
149                 Some(x) => x,
150                 None => continue,
151             };
152             let id = if let Some(x) = self.def_map.get(&def) {
153                 *x
154             } else {
155                 let x = self.tokens.insert(TokenStaticData {
156                     hover: hover_for_definition(&sema, file_id, def, &node, &hover_config),
157                     definition: def
158                         .try_to_nav(self.db)
159                         .map(|x| FileRange { file_id: x.file_id, range: x.focus_or_full_range() }),
160                     references: vec![],
161                     moniker: current_crate.and_then(|cc| def_to_moniker(self.db, def, cc)),
162                 });
163                 self.def_map.insert(def, x);
164                 x
165             };
166             let token = self.tokens.get_mut(id).unwrap();
167             token.references.push(ReferenceData {
168                 range: FileRange { range, file_id },
169                 is_definition: match def.try_to_nav(self.db) {
170                     Some(x) => x.file_id == file_id && x.focus_or_full_range() == range,
171                     None => false,
172                 },
173             });
174             result.tokens.push((range, id));
175         }
176         self.files.push(result);
177     }
178
179     pub fn compute(analysis: &Analysis) -> StaticIndex<'_> {
180         let db = &*analysis.db;
181         let work = all_modules(db).into_iter().filter(|module| {
182             let file_id = module.definition_source(db).file_id.original_file(db);
183             let source_root = db.file_source_root(file_id);
184             let source_root = db.source_root(source_root);
185             !source_root.is_library
186         });
187         let mut this = StaticIndex {
188             files: vec![],
189             tokens: Default::default(),
190             analysis,
191             db,
192             def_map: Default::default(),
193         };
194         let mut visited_files = FxHashSet::default();
195         for module in work {
196             let file_id = module.definition_source(db).file_id.original_file(db);
197             if visited_files.contains(&file_id) {
198                 continue;
199             }
200             this.add_file(file_id);
201             // mark the file
202             visited_files.insert(file_id);
203         }
204         this
205     }
206 }
207
208 fn get_definition(sema: &Semantics<'_, RootDatabase>, token: SyntaxToken) -> Option<Definition> {
209     for token in sema.descend_into_macros(token) {
210         let def = IdentClass::classify_token(sema, &token).map(IdentClass::definitions_no_ops);
211         if let Some(&[x]) = def.as_deref() {
212             return Some(x);
213         } else {
214             continue;
215         };
216     }
217     None
218 }
219
220 #[cfg(test)]
221 mod tests {
222     use crate::{fixture, StaticIndex};
223     use ide_db::base_db::FileRange;
224     use std::collections::HashSet;
225     use syntax::TextSize;
226
227     fn check_all_ranges(ra_fixture: &str) {
228         let (analysis, ranges) = fixture::annotations_without_marker(ra_fixture);
229         let s = StaticIndex::compute(&analysis);
230         let mut range_set: HashSet<_> = ranges.iter().map(|x| x.0).collect();
231         for f in s.files {
232             for (range, _) in f.tokens {
233                 let x = FileRange { file_id: f.file_id, range };
234                 if !range_set.contains(&x) {
235                     panic!("additional range {:?}", x);
236                 }
237                 range_set.remove(&x);
238             }
239         }
240         if !range_set.is_empty() {
241             panic!("unfound ranges {:?}", range_set);
242         }
243     }
244
245     fn check_definitions(ra_fixture: &str) {
246         let (analysis, ranges) = fixture::annotations_without_marker(ra_fixture);
247         let s = StaticIndex::compute(&analysis);
248         let mut range_set: HashSet<_> = ranges.iter().map(|x| x.0).collect();
249         for (_, t) in s.tokens.iter() {
250             if let Some(x) = t.definition {
251                 if x.range.start() == TextSize::from(0) {
252                     // ignore definitions that are whole of file
253                     continue;
254                 }
255                 if !range_set.contains(&x) {
256                     panic!("additional definition {:?}", x);
257                 }
258                 range_set.remove(&x);
259             }
260         }
261         if !range_set.is_empty() {
262             panic!("unfound definitions {:?}", range_set);
263         }
264     }
265
266     #[test]
267     fn struct_and_enum() {
268         check_all_ranges(
269             r#"
270 struct Foo;
271      //^^^
272 enum E { X(Foo) }
273    //^   ^ ^^^
274 "#,
275         );
276         check_definitions(
277             r#"
278 struct Foo;
279      //^^^
280 enum E { X(Foo) }
281    //^   ^
282 "#,
283         );
284     }
285
286     #[test]
287     fn multi_crate() {
288         check_definitions(
289             r#"
290 //- /main.rs crate:main deps:foo
291
292
293 use foo::func;
294
295 fn main() {
296  //^^^^
297     func();
298 }
299 //- /foo/lib.rs crate:foo
300
301 pub func() {
302
303 }
304 "#,
305         );
306     }
307
308     #[test]
309     fn derives() {
310         check_all_ranges(
311             r#"
312 //- minicore:derive
313 #[rustc_builtin_macro]
314 //^^^^^^^^^^^^^^^^^^^
315 pub macro Copy {}
316         //^^^^
317 #[derive(Copy)]
318 //^^^^^^ ^^^^
319 struct Hello(i32);
320      //^^^^^ ^^^
321 "#,
322         );
323     }
324 }