]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/static_index.rs
Merge #11579
[rust.git] / 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     RootDatabase,
11 };
12 use rustc_hash::FxHashSet;
13 use syntax::{AstNode, SyntaxKind::*, SyntaxToken, TextRange, T};
14
15 use crate::moniker::{crate_for_file, def_to_moniker, MonikerResult};
16 use crate::{
17     hover::hover_for_definition, Analysis, Fold, HoverConfig, HoverDocFormat, HoverResult,
18     InlayHint, InlayHintsConfig, 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                     type_hints: true,
109                     parameter_hints: true,
110                     chaining_hints: true,
111                     hide_named_constructor_hints: false,
112                     max_length: Some(25),
113                 },
114                 file_id,
115             )
116             .unwrap();
117         // hovers
118         let sema = hir::Semantics::new(self.db);
119         let tokens_or_nodes = sema.parse(file_id).syntax().clone();
120         let tokens = tokens_or_nodes.descendants_with_tokens().filter_map(|x| match x {
121             syntax::NodeOrToken::Node(_) => None,
122             syntax::NodeOrToken::Token(x) => Some(x),
123         });
124         let hover_config =
125             HoverConfig { links_in_hover: true, documentation: Some(HoverDocFormat::Markdown) };
126         let tokens = tokens.filter(|token| {
127             matches!(
128                 token.kind(),
129                 IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate]
130             )
131         });
132         let mut result = StaticIndexedFile { file_id, inlay_hints, folds, tokens: vec![] };
133         for token in tokens {
134             let range = token.text_range();
135             let node = token.parent().unwrap();
136             let def = match get_definition(&sema, token.clone()) {
137                 Some(x) => x,
138                 None => continue,
139             };
140             let id = if let Some(x) = self.def_map.get(&def) {
141                 *x
142             } else {
143                 let x = self.tokens.insert(TokenStaticData {
144                     hover: hover_for_definition(&sema, file_id, def, &node, &hover_config),
145                     definition: def
146                         .try_to_nav(self.db)
147                         .map(|x| FileRange { file_id: x.file_id, range: x.focus_or_full_range() }),
148                     references: vec![],
149                     moniker: current_crate.and_then(|cc| def_to_moniker(self.db, def, cc)),
150                 });
151                 self.def_map.insert(def, x);
152                 x
153             };
154             let token = self.tokens.get_mut(id).unwrap();
155             token.references.push(ReferenceData {
156                 range: FileRange { range, file_id },
157                 is_definition: match def.try_to_nav(self.db) {
158                     Some(x) => x.file_id == file_id && x.focus_or_full_range() == range,
159                     None => false,
160                 },
161             });
162             result.tokens.push((range, id));
163         }
164         self.files.push(result);
165     }
166
167     pub fn compute(analysis: &Analysis) -> StaticIndex {
168         let db = &*analysis.db;
169         let work = all_modules(db).into_iter().filter(|module| {
170             let file_id = module.definition_source(db).file_id.original_file(db);
171             let source_root = db.file_source_root(file_id);
172             let source_root = db.source_root(source_root);
173             !source_root.is_library
174         });
175         let mut this = StaticIndex {
176             files: vec![],
177             tokens: Default::default(),
178             analysis,
179             db,
180             def_map: Default::default(),
181         };
182         let mut visited_files = FxHashSet::default();
183         for module in work {
184             let file_id = module.definition_source(db).file_id.original_file(db);
185             if visited_files.contains(&file_id) {
186                 continue;
187             }
188             this.add_file(file_id);
189             // mark the file
190             visited_files.insert(file_id);
191         }
192         this
193     }
194 }
195
196 fn get_definition(sema: &Semantics<RootDatabase>, token: SyntaxToken) -> Option<Definition> {
197     for token in sema.descend_into_macros(token) {
198         let def = IdentClass::classify_token(sema, &token).map(IdentClass::definitions);
199         if let Some(&[x]) = def.as_deref() {
200             return Some(x);
201         } else {
202             continue;
203         };
204     }
205     None
206 }
207
208 #[cfg(test)]
209 mod tests {
210     use crate::{fixture, StaticIndex};
211     use ide_db::base_db::FileRange;
212     use std::collections::HashSet;
213     use syntax::TextSize;
214
215     fn check_all_ranges(ra_fixture: &str) {
216         let (analysis, ranges) = fixture::annotations_without_marker(ra_fixture);
217         let s = StaticIndex::compute(&analysis);
218         let mut range_set: HashSet<_> = ranges.iter().map(|x| x.0).collect();
219         for f in s.files {
220             for (range, _) in f.tokens {
221                 let x = FileRange { file_id: f.file_id, range };
222                 if !range_set.contains(&x) {
223                     panic!("additional range {:?}", x);
224                 }
225                 range_set.remove(&x);
226             }
227         }
228         if !range_set.is_empty() {
229             panic!("unfound ranges {:?}", range_set);
230         }
231     }
232
233     fn check_definitions(ra_fixture: &str) {
234         let (analysis, ranges) = fixture::annotations_without_marker(ra_fixture);
235         let s = StaticIndex::compute(&analysis);
236         let mut range_set: HashSet<_> = ranges.iter().map(|x| x.0).collect();
237         for (_, t) in s.tokens.iter() {
238             if let Some(x) = t.definition {
239                 if x.range.start() == TextSize::from(0) {
240                     // ignore definitions that are whole of file
241                     continue;
242                 }
243                 if !range_set.contains(&x) {
244                     panic!("additional definition {:?}", x);
245                 }
246                 range_set.remove(&x);
247             }
248         }
249         if !range_set.is_empty() {
250             panic!("unfound definitions {:?}", range_set);
251         }
252     }
253
254     #[test]
255     fn struct_and_enum() {
256         check_all_ranges(
257             r#"
258 struct Foo;
259      //^^^
260 enum E { X(Foo) }
261    //^   ^ ^^^
262 "#,
263         );
264         check_definitions(
265             r#"
266 struct Foo;
267      //^^^
268 enum E { X(Foo) }
269    //^   ^
270 "#,
271         );
272     }
273
274     #[test]
275     fn multi_crate() {
276         check_definitions(
277             r#"
278 //- /main.rs crate:main deps:foo
279
280
281 use foo::func;
282
283 fn main() {
284  //^^^^
285     func();
286 }
287 //- /foo/lib.rs crate:foo
288
289 pub func() {
290
291 }
292 "#,
293         );
294     }
295
296     #[test]
297     fn derives() {
298         check_all_ranges(
299             r#"
300 //- minicore:derive
301 #[rustc_builtin_macro]
302 //^^^^^^^^^^^^^^^^^^^
303 pub macro Copy {}
304         //^^^^
305 #[derive(Copy)]
306 //^^^^^^ ^^^^
307 struct Hello(i32);
308      //^^^^^ ^^^
309 "#,
310         );
311     }
312 }