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, salsa},
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 = salsa::attach(sema.db, || {
232                    self.tokens.insert(TokenStaticData {
233                        documentation: documentation_for_definition(&sema, def, scope_node),
234                        hover: Some(hover_for_definition(
235                            &sema,
236                            file_id,
237                            def,
238                            None,
239                            scope_node,
240                            None,
241                            false,
242                            &hover_config,
243                            edition,
244                            display_target,
245                        )),
246                        definition: def.try_to_nav(self.db).map(UpmappingResult::call_site).map(
247                            |it| FileRange { file_id: it.file_id, range: it.focus_or_full_range() },
248                        ),
249                        references: vec![],
250                        moniker: current_crate.and_then(|cc| def_to_moniker(self.db, def, cc)),
251                        display_name: def
252                            .name(self.db)
253                            .map(|name| name.display(self.db, edition).to_string()),
254                        signature: Some(def.label(self.db, display_target)),
255                        kind: def_to_kind(self.db, def),
256                    })
257                });
258                self.def_map.insert(def, it);
259                it
260            };
261            let token = self.tokens.get_mut(id).unwrap();
262            token.references.push(ReferenceData {
263                range: FileRange { range, file_id },
264                is_definition: match def.try_to_nav(self.db).map(UpmappingResult::call_site) {
265                    Some(it) => it.file_id == file_id && it.focus_or_full_range() == range,
266                    None => false,
267                },
268            });
269            result.tokens.push((range, id));
270        };
271
272        if let Some(module) = sema.file_to_module_def(file_id) {
273            let def = Definition::Module(module);
274            let range = root.text_range();
275            add_token(def, range, &root);
276        }
277
278        for token in tokens {
279            let range = token.text_range();
280            let node = token.parent().unwrap();
281            match get_definitions(&sema, token.clone()) {
282                Some(it) => {
283                    for i in it {
284                        add_token(i, range, &node);
285                    }
286                }
287                None => continue,
288            };
289        }
290        self.files.push(result);
291    }
292
293    pub fn compute<'a>(
294        analysis: &'a Analysis,
295        vendored_libs_config: VendoredLibrariesConfig<'_>,
296    ) -> StaticIndex<'a> {
297        let db = &analysis.db;
298        let work = all_modules(db).into_iter().filter(|module| {
299            let file_id = module.definition_source_file_id(db).original_file(db);
300            let source_root = 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#[cfg(test)]
333mod tests {
334    use crate::{StaticIndex, fixture};
335    use ide_db::{FileRange, FxHashMap, FxHashSet, base_db::VfsPath};
336    use syntax::TextSize;
337
338    use super::VendoredLibrariesConfig;
339
340    fn check_all_ranges(
341        #[rust_analyzer::rust_fixture] ra_fixture: &str,
342        vendored_libs_config: VendoredLibrariesConfig<'_>,
343    ) {
344        let (analysis, ranges) = fixture::annotations_without_marker(ra_fixture);
345        let s = StaticIndex::compute(&analysis, vendored_libs_config);
346        let mut range_set: FxHashSet<_> = ranges.iter().map(|it| it.0).collect();
347        for f in s.files {
348            for (range, _) in f.tokens {
349                if range.start() == TextSize::from(0) {
350                    // ignore whole file range corresponding to module definition
351                    continue;
352                }
353                let it = FileRange { file_id: f.file_id, range };
354                if !range_set.contains(&it) {
355                    panic!("additional range {it:?}");
356                }
357                range_set.remove(&it);
358            }
359        }
360        if !range_set.is_empty() {
361            panic!("unfound ranges {range_set:?}");
362        }
363    }
364
365    #[track_caller]
366    fn check_definitions(
367        #[rust_analyzer::rust_fixture] ra_fixture: &str,
368        vendored_libs_config: VendoredLibrariesConfig<'_>,
369    ) {
370        let (analysis, ranges) = fixture::annotations_without_marker(ra_fixture);
371        let s = StaticIndex::compute(&analysis, vendored_libs_config);
372        let mut range_set: FxHashSet<_> = ranges.iter().map(|it| it.0).collect();
373        for (_, t) in s.tokens.iter() {
374            if let Some(t) = t.definition {
375                if t.range.start() == TextSize::from(0) {
376                    // ignore definitions that are whole of file
377                    continue;
378                }
379                if !range_set.contains(&t) {
380                    panic!("additional definition {t:?}");
381                }
382                range_set.remove(&t);
383            }
384        }
385        if !range_set.is_empty() {
386            panic!("unfound definitions {range_set:?}");
387        }
388    }
389
390    #[track_caller]
391    fn check_references(
392        #[rust_analyzer::rust_fixture] ra_fixture: &str,
393        vendored_libs_config: VendoredLibrariesConfig<'_>,
394    ) {
395        let (analysis, ranges) = fixture::annotations_without_marker(ra_fixture);
396        let s = StaticIndex::compute(&analysis, vendored_libs_config);
397        let mut range_set: FxHashMap<_, i32> = ranges.iter().map(|it| (it.0, 0)).collect();
398
399        // Make sure that all references have at least one range. We use a HashMap instead of a
400        // a HashSet so that we can have more than one reference at the same range.
401        for (_, t) in s.tokens.iter() {
402            for r in &t.references {
403                if r.is_definition {
404                    continue;
405                }
406                if r.range.range.start() == TextSize::from(0) {
407                    // ignore whole file range corresponding to module definition
408                    continue;
409                }
410                match range_set.entry(r.range) {
411                    std::collections::hash_map::Entry::Occupied(mut entry) => {
412                        let count = entry.get_mut();
413                        *count += 1;
414                    }
415                    std::collections::hash_map::Entry::Vacant(_) => {
416                        panic!("additional reference {r:?}");
417                    }
418                }
419            }
420        }
421        for (range, count) in range_set.iter() {
422            if *count == 0 {
423                panic!("unfound reference {range:?}");
424            }
425        }
426    }
427
428    #[test]
429    fn field_initialization() {
430        check_references(
431            r#"
432struct Point {
433    x: f64,
434     //^^^
435    y: f64,
436     //^^^
437}
438    fn foo() {
439        let x = 5.;
440        let y = 10.;
441        let mut p = Point { x, y };
442                  //^^^^^   ^  ^
443        p.x = 9.;
444      //^ ^
445        p.y = 10.;
446      //^ ^
447    }
448"#,
449            VendoredLibrariesConfig::Included {
450                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
451            },
452        );
453    }
454
455    #[test]
456    fn struct_and_enum() {
457        check_all_ranges(
458            r#"
459struct Foo;
460     //^^^
461enum E { X(Foo) }
462   //^   ^ ^^^
463"#,
464            VendoredLibrariesConfig::Included {
465                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
466            },
467        );
468        check_definitions(
469            r#"
470struct Foo;
471     //^^^
472enum E { X(Foo) }
473   //^   ^
474"#,
475            VendoredLibrariesConfig::Included {
476                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
477            },
478        );
479
480        check_references(
481            r#"
482struct Foo;
483enum E { X(Foo) }
484   //      ^^^
485"#,
486            VendoredLibrariesConfig::Included {
487                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
488            },
489        );
490    }
491
492    #[test]
493    fn multi_crate() {
494        check_definitions(
495            r#"
496//- /workspace/main.rs crate:main deps:foo
497
498
499use foo::func;
500
501fn main() {
502 //^^^^
503    func();
504}
505//- /workspace/foo/lib.rs crate:foo
506
507pub func() {
508
509}
510"#,
511            VendoredLibrariesConfig::Included {
512                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
513            },
514        );
515    }
516
517    #[test]
518    fn vendored_crate() {
519        check_all_ranges(
520            r#"
521//- /workspace/main.rs crate:main deps:external,vendored
522struct Main(i32);
523     //^^^^ ^^^
524
525//- /external/lib.rs new_source_root:library crate:external@0.1.0,https://a.b/foo.git library
526struct ExternalLibrary(i32);
527
528//- /workspace/vendored/lib.rs new_source_root:library crate:vendored@0.1.0,https://a.b/bar.git library
529struct VendoredLibrary(i32);
530     //^^^^^^^^^^^^^^^ ^^^
531"#,
532            VendoredLibrariesConfig::Included {
533                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
534            },
535        );
536    }
537
538    #[test]
539    fn vendored_crate_excluded() {
540        check_all_ranges(
541            r#"
542//- /workspace/main.rs crate:main deps:external,vendored
543struct Main(i32);
544     //^^^^ ^^^
545
546//- /external/lib.rs new_source_root:library crate:external@0.1.0,https://a.b/foo.git library
547struct ExternalLibrary(i32);
548
549//- /workspace/vendored/lib.rs new_source_root:library crate:vendored@0.1.0,https://a.b/bar.git library
550struct VendoredLibrary(i32);
551"#,
552            VendoredLibrariesConfig::Excluded,
553        )
554    }
555
556    #[test]
557    fn derives() {
558        check_all_ranges(
559            r#"
560//- minicore:derive
561#[rustc_builtin_macro]
562//^^^^^^^^^^^^^^^^^^^
563pub macro Copy {}
564        //^^^^
565#[derive(Copy)]
566//^^^^^^ ^^^^
567struct Hello(i32);
568     //^^^^^ ^^^
569"#,
570            VendoredLibrariesConfig::Included {
571                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
572            },
573        );
574    }
575}