ide/
static_index.rs

1//! This module provides `StaticIndex` which is used for powering
2//! read-only code browsers and emitting LSIF
3
4use arrayvec::ArrayVec;
5use hir::{Crate, Module, Semantics, db::HirDatabase};
6use ide_db::{
7    FileId, FileRange, FxHashMap, FxHashSet, RootDatabase,
8    base_db::{RootQueryDb, SourceDatabase, VfsPath},
9    defs::{Definition, IdentClass},
10    documentation::Documentation,
11    famous_defs::FamousDefs,
12};
13use span::Edition;
14use syntax::{AstNode, SyntaxKind::*, SyntaxNode, SyntaxToken, T, TextRange};
15
16use crate::navigation_target::UpmappingResult;
17use crate::{
18    Analysis, Fold, HoverConfig, HoverResult, InlayHint, InlayHintsConfig, TryToNav,
19    hover::{SubstTyLen, hover_for_definition},
20    inlay_hints::{AdjustmentHintsMode, InlayFieldsToResolve},
21    moniker::{MonikerResult, SymbolInformationKind, def_to_kind, def_to_moniker},
22    parent_module::crates_for,
23};
24
25/// A static representation of fully analyzed source code.
26///
27/// The intended use-case is powering read-only code browsers and emitting LSIF/SCIP.
28#[derive(Debug)]
29pub struct StaticIndex<'a> {
30    pub files: Vec<StaticIndexedFile>,
31    pub tokens: TokenStore,
32    analysis: &'a Analysis,
33    db: &'a RootDatabase,
34    def_map: FxHashMap<Definition, TokenId>,
35}
36
37#[derive(Debug)]
38pub struct ReferenceData {
39    pub range: FileRange,
40    pub is_definition: bool,
41}
42
43#[derive(Debug)]
44pub struct TokenStaticData {
45    pub documentation: Option<Documentation>,
46    pub hover: Option<HoverResult>,
47    pub definition: Option<FileRange>,
48    pub references: Vec<ReferenceData>,
49    pub moniker: Option<MonikerResult>,
50    pub display_name: Option<String>,
51    pub signature: Option<String>,
52    pub kind: SymbolInformationKind,
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
56pub struct TokenId(usize);
57
58impl TokenId {
59    pub fn raw(self) -> usize {
60        self.0
61    }
62}
63
64#[derive(Default, Debug)]
65pub struct TokenStore(Vec<TokenStaticData>);
66
67impl TokenStore {
68    pub fn insert(&mut self, data: TokenStaticData) -> TokenId {
69        let id = TokenId(self.0.len());
70        self.0.push(data);
71        id
72    }
73
74    pub fn get_mut(&mut self, id: TokenId) -> Option<&mut TokenStaticData> {
75        self.0.get_mut(id.0)
76    }
77
78    pub fn get(&self, id: TokenId) -> Option<&TokenStaticData> {
79        self.0.get(id.0)
80    }
81
82    pub fn iter(self) -> impl Iterator<Item = (TokenId, TokenStaticData)> {
83        self.0.into_iter().enumerate().map(|(id, data)| (TokenId(id), data))
84    }
85}
86
87#[derive(Debug)]
88pub struct StaticIndexedFile {
89    pub file_id: FileId,
90    pub folds: Vec<Fold>,
91    pub inlay_hints: Vec<InlayHint>,
92    pub tokens: Vec<(TextRange, TokenId)>,
93}
94
95fn all_modules(db: &dyn HirDatabase) -> Vec<Module> {
96    let mut worklist: Vec<_> =
97        Crate::all(db).into_iter().map(|krate| krate.root_module()).collect();
98    let mut modules = Vec::new();
99
100    while let Some(module) = worklist.pop() {
101        modules.push(module);
102        worklist.extend(module.children(db));
103    }
104
105    modules
106}
107
108fn documentation_for_definition(
109    sema: &Semantics<'_, RootDatabase>,
110    def: Definition,
111    scope_node: &SyntaxNode,
112) -> Option<Documentation> {
113    let famous_defs = match &def {
114        Definition::BuiltinType(_) => Some(FamousDefs(sema, sema.scope(scope_node)?.krate())),
115        _ => None,
116    };
117
118    def.docs(
119        sema.db,
120        famous_defs.as_ref(),
121        def.krate(sema.db)
122            .unwrap_or_else(|| {
123                (*sema.db.all_crates().last().expect("no crate graph present")).into()
124            })
125            .to_display_target(sema.db),
126    )
127}
128
129// FIXME: This is a weird function
130fn get_definitions(
131    sema: &Semantics<'_, RootDatabase>,
132    token: SyntaxToken,
133) -> Option<ArrayVec<Definition, 2>> {
134    for token in sema.descend_into_macros_exact(token) {
135        let def = IdentClass::classify_token(sema, &token).map(IdentClass::definitions_no_ops);
136        if let Some(defs) = def
137            && !defs.is_empty()
138        {
139            return Some(defs);
140        }
141    }
142    None
143}
144
145pub enum VendoredLibrariesConfig<'a> {
146    Included { workspace_root: &'a VfsPath },
147    Excluded,
148}
149
150impl StaticIndex<'_> {
151    fn add_file(&mut self, file_id: FileId) {
152        let current_crate = crates_for(self.db, file_id).pop().map(Into::into);
153        let folds = self.analysis.folding_ranges(file_id).unwrap();
154        let inlay_hints = self
155            .analysis
156            .inlay_hints(
157                &InlayHintsConfig {
158                    render_colons: true,
159                    discriminant_hints: crate::DiscriminantHints::Fieldless,
160                    type_hints: true,
161                    sized_bound: false,
162                    parameter_hints: true,
163                    generic_parameter_hints: crate::GenericParameterHints {
164                        type_hints: false,
165                        lifetime_hints: false,
166                        const_hints: true,
167                    },
168                    chaining_hints: true,
169                    closure_return_type_hints: crate::ClosureReturnTypeHints::WithBlock,
170                    lifetime_elision_hints: crate::LifetimeElisionHints::Never,
171                    adjustment_hints: crate::AdjustmentHints::Never,
172                    adjustment_hints_disable_reborrows: true,
173                    adjustment_hints_mode: AdjustmentHintsMode::Prefix,
174                    adjustment_hints_hide_outside_unsafe: false,
175                    implicit_drop_hints: false,
176                    hide_named_constructor_hints: false,
177                    hide_closure_initialization_hints: false,
178                    hide_closure_parameter_hints: false,
179                    closure_style: hir::ClosureStyle::ImplFn,
180                    param_names_for_lifetime_elision_hints: false,
181                    binding_mode_hints: false,
182                    max_length: Some(25),
183                    closure_capture_hints: false,
184                    closing_brace_hints_min_lines: Some(25),
185                    fields_to_resolve: InlayFieldsToResolve::empty(),
186                    range_exclusive_hints: false,
187                },
188                file_id,
189                None,
190            )
191            .unwrap();
192        // hovers
193        let sema = hir::Semantics::new(self.db);
194        let root = sema.parse_guess_edition(file_id).syntax().clone();
195        let edition = sema
196            .attach_first_edition(file_id)
197            .map(|it| it.edition(self.db))
198            .unwrap_or(Edition::CURRENT);
199        let display_target = match sema.first_crate(file_id) {
200            Some(krate) => krate.to_display_target(sema.db),
201            None => return,
202        };
203        let tokens = root.descendants_with_tokens().filter_map(|it| match it {
204            syntax::NodeOrToken::Node(_) => None,
205            syntax::NodeOrToken::Token(it) => Some(it),
206        });
207        let hover_config = HoverConfig {
208            links_in_hover: true,
209            memory_layout: None,
210            documentation: true,
211            keywords: true,
212            format: crate::HoverDocFormat::Markdown,
213            max_trait_assoc_items_count: None,
214            max_fields_count: Some(5),
215            max_enum_variants_count: Some(5),
216            max_subst_ty_len: SubstTyLen::Unlimited,
217            show_drop_glue: true,
218        };
219        let tokens = tokens.filter(|token| {
220            matches!(
221                token.kind(),
222                IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] | T![Self]
223            )
224        });
225        let mut result = StaticIndexedFile { file_id, inlay_hints, folds, tokens: vec![] };
226
227        let mut add_token = |def: Definition, range: TextRange, scope_node: &SyntaxNode| {
228            let id = if let Some(it) = self.def_map.get(&def) {
229                *it
230            } else {
231                let it = self.tokens.insert(TokenStaticData {
232                    documentation: documentation_for_definition(&sema, def, scope_node),
233                    hover: Some(hover_for_definition(
234                        &sema,
235                        file_id,
236                        def,
237                        None,
238                        scope_node,
239                        None,
240                        false,
241                        &hover_config,
242                        edition,
243                        display_target,
244                    )),
245                    definition: def.try_to_nav(&sema).map(UpmappingResult::call_site).map(|it| {
246                        FileRange { file_id: it.file_id, range: it.focus_or_full_range() }
247                    }),
248                    references: vec![],
249                    moniker: current_crate.and_then(|cc| def_to_moniker(self.db, def, cc)),
250                    display_name: def
251                        .name(self.db)
252                        .map(|name| name.display(self.db, edition).to_string()),
253                    signature: Some(def.label(self.db, display_target)),
254                    kind: def_to_kind(self.db, def),
255                });
256                self.def_map.insert(def, it);
257                it
258            };
259            let token = self.tokens.get_mut(id).unwrap();
260            token.references.push(ReferenceData {
261                range: FileRange { range, file_id },
262                is_definition: match def.try_to_nav(&sema).map(UpmappingResult::call_site) {
263                    Some(it) => it.file_id == file_id && it.focus_or_full_range() == range,
264                    None => false,
265                },
266            });
267            result.tokens.push((range, id));
268        };
269
270        if let Some(module) = sema.file_to_module_def(file_id) {
271            let def = Definition::Module(module);
272            let range = root.text_range();
273            add_token(def, range, &root);
274        }
275
276        for token in tokens {
277            let range = token.text_range();
278            let node = token.parent().unwrap();
279            match hir::attach_db(self.db, || get_definitions(&sema, token.clone())) {
280                Some(it) => {
281                    for i in it {
282                        add_token(i, range, &node);
283                    }
284                }
285                None => continue,
286            };
287        }
288        self.files.push(result);
289    }
290
291    pub fn compute<'a>(
292        analysis: &'a Analysis,
293        vendored_libs_config: VendoredLibrariesConfig<'_>,
294    ) -> StaticIndex<'a> {
295        let db = &analysis.db;
296        hir::attach_db(db, || {
297            let work = all_modules(db).into_iter().filter(|module| {
298                let file_id = module.definition_source_file_id(db).original_file(db);
299                let source_root =
300                    db.file_source_root(file_id.file_id(&analysis.db)).source_root_id(db);
301                let source_root = db.source_root(source_root).source_root(db);
302                let is_vendored = match vendored_libs_config {
303                    VendoredLibrariesConfig::Included { workspace_root } => source_root
304                        .path_for_file(&file_id.file_id(&analysis.db))
305                        .is_some_and(|module_path| module_path.starts_with(workspace_root)),
306                    VendoredLibrariesConfig::Excluded => false,
307                };
308
309                !source_root.is_library || is_vendored
310            });
311            let mut this = StaticIndex {
312                files: vec![],
313                tokens: Default::default(),
314                analysis,
315                db,
316                def_map: Default::default(),
317            };
318            let mut visited_files = FxHashSet::default();
319            for module in work {
320                let file_id = module.definition_source_file_id(db).original_file(db);
321                if visited_files.contains(&file_id) {
322                    continue;
323                }
324                this.add_file(file_id.file_id(&analysis.db));
325                // mark the file
326                visited_files.insert(file_id);
327            }
328            this
329        })
330    }
331}
332
333#[cfg(test)]
334mod tests {
335    use crate::{StaticIndex, fixture};
336    use ide_db::{FileRange, FxHashMap, FxHashSet, base_db::VfsPath};
337    use syntax::TextSize;
338
339    use super::VendoredLibrariesConfig;
340
341    fn check_all_ranges(
342        #[rust_analyzer::rust_fixture] ra_fixture: &str,
343        vendored_libs_config: VendoredLibrariesConfig<'_>,
344    ) {
345        let (analysis, ranges) = fixture::annotations_without_marker(ra_fixture);
346        let s = StaticIndex::compute(&analysis, vendored_libs_config);
347        let mut range_set: FxHashSet<_> = ranges.iter().map(|it| it.0).collect();
348        for f in s.files {
349            for (range, _) in f.tokens {
350                if range.start() == TextSize::from(0) {
351                    // ignore whole file range corresponding to module definition
352                    continue;
353                }
354                let it = FileRange { file_id: f.file_id, range };
355                if !range_set.contains(&it) {
356                    panic!("additional range {it:?}");
357                }
358                range_set.remove(&it);
359            }
360        }
361        if !range_set.is_empty() {
362            panic!("unfound ranges {range_set:?}");
363        }
364    }
365
366    #[track_caller]
367    fn check_definitions(
368        #[rust_analyzer::rust_fixture] ra_fixture: &str,
369        vendored_libs_config: VendoredLibrariesConfig<'_>,
370    ) {
371        let (analysis, ranges) = fixture::annotations_without_marker(ra_fixture);
372        let s = StaticIndex::compute(&analysis, vendored_libs_config);
373        let mut range_set: FxHashSet<_> = ranges.iter().map(|it| it.0).collect();
374        for (_, t) in s.tokens.iter() {
375            if let Some(t) = t.definition {
376                if t.range.start() == TextSize::from(0) {
377                    // ignore definitions that are whole of file
378                    continue;
379                }
380                if !range_set.contains(&t) {
381                    panic!("additional definition {t:?}");
382                }
383                range_set.remove(&t);
384            }
385        }
386        if !range_set.is_empty() {
387            panic!("unfound definitions {range_set:?}");
388        }
389    }
390
391    #[track_caller]
392    fn check_references(
393        #[rust_analyzer::rust_fixture] ra_fixture: &str,
394        vendored_libs_config: VendoredLibrariesConfig<'_>,
395    ) {
396        let (analysis, ranges) = fixture::annotations_without_marker(ra_fixture);
397        let s = StaticIndex::compute(&analysis, vendored_libs_config);
398        let mut range_set: FxHashMap<_, i32> = ranges.iter().map(|it| (it.0, 0)).collect();
399
400        // Make sure that all references have at least one range. We use a HashMap instead of a
401        // a HashSet so that we can have more than one reference at the same range.
402        for (_, t) in s.tokens.iter() {
403            for r in &t.references {
404                if r.is_definition {
405                    continue;
406                }
407                if r.range.range.start() == TextSize::from(0) {
408                    // ignore whole file range corresponding to module definition
409                    continue;
410                }
411                match range_set.entry(r.range) {
412                    std::collections::hash_map::Entry::Occupied(mut entry) => {
413                        let count = entry.get_mut();
414                        *count += 1;
415                    }
416                    std::collections::hash_map::Entry::Vacant(_) => {
417                        panic!("additional reference {r:?}");
418                    }
419                }
420            }
421        }
422        for (range, count) in range_set.iter() {
423            if *count == 0 {
424                panic!("unfound reference {range:?}");
425            }
426        }
427    }
428
429    #[test]
430    fn field_initialization() {
431        check_references(
432            r#"
433struct Point {
434    x: f64,
435     //^^^
436    y: f64,
437     //^^^
438}
439    fn foo() {
440        let x = 5.;
441        let y = 10.;
442        let mut p = Point { x, y };
443                  //^^^^^   ^  ^
444        p.x = 9.;
445      //^ ^
446        p.y = 10.;
447      //^ ^
448    }
449"#,
450            VendoredLibrariesConfig::Included {
451                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
452            },
453        );
454    }
455
456    #[test]
457    fn struct_and_enum() {
458        check_all_ranges(
459            r#"
460struct Foo;
461     //^^^
462enum E { X(Foo) }
463   //^   ^ ^^^
464"#,
465            VendoredLibrariesConfig::Included {
466                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
467            },
468        );
469        check_definitions(
470            r#"
471struct Foo;
472     //^^^
473enum E { X(Foo) }
474   //^   ^
475"#,
476            VendoredLibrariesConfig::Included {
477                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
478            },
479        );
480
481        check_references(
482            r#"
483struct Foo;
484enum E { X(Foo) }
485   //      ^^^
486"#,
487            VendoredLibrariesConfig::Included {
488                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
489            },
490        );
491    }
492
493    #[test]
494    fn multi_crate() {
495        check_definitions(
496            r#"
497//- /workspace/main.rs crate:main deps:foo
498
499
500use foo::func;
501
502fn main() {
503 //^^^^
504    func();
505}
506//- /workspace/foo/lib.rs crate:foo
507
508pub func() {
509
510}
511"#,
512            VendoredLibrariesConfig::Included {
513                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
514            },
515        );
516    }
517
518    #[test]
519    fn vendored_crate() {
520        check_all_ranges(
521            r#"
522//- /workspace/main.rs crate:main deps:external,vendored
523struct Main(i32);
524     //^^^^ ^^^
525
526//- /external/lib.rs new_source_root:library crate:external@0.1.0,https://a.b/foo.git library
527struct ExternalLibrary(i32);
528
529//- /workspace/vendored/lib.rs new_source_root:library crate:vendored@0.1.0,https://a.b/bar.git library
530struct VendoredLibrary(i32);
531     //^^^^^^^^^^^^^^^ ^^^
532"#,
533            VendoredLibrariesConfig::Included {
534                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
535            },
536        );
537    }
538
539    #[test]
540    fn vendored_crate_excluded() {
541        check_all_ranges(
542            r#"
543//- /workspace/main.rs crate:main deps:external,vendored
544struct Main(i32);
545     //^^^^ ^^^
546
547//- /external/lib.rs new_source_root:library crate:external@0.1.0,https://a.b/foo.git library
548struct ExternalLibrary(i32);
549
550//- /workspace/vendored/lib.rs new_source_root:library crate:vendored@0.1.0,https://a.b/bar.git library
551struct VendoredLibrary(i32);
552"#,
553            VendoredLibrariesConfig::Excluded,
554        )
555    }
556
557    #[test]
558    fn derives() {
559        check_all_ranges(
560            r#"
561//- minicore:derive
562#[rustc_builtin_macro]
563//^^^^^^^^^^^^^^^^^^^
564pub macro Copy {}
565        //^^^^
566#[derive(Copy)]
567//^^^^^^ ^^^^
568struct Hello(i32);
569     //^^^^^ ^^^
570"#,
571            VendoredLibrariesConfig::Included {
572                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
573            },
574        );
575    }
576}