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, MiniCore, 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                    implied_dyn_trait_hints: false,
177                    hide_named_constructor_hints: false,
178                    hide_closure_initialization_hints: false,
179                    hide_closure_parameter_hints: false,
180                    closure_style: hir::ClosureStyle::ImplFn,
181                    param_names_for_lifetime_elision_hints: false,
182                    binding_mode_hints: false,
183                    max_length: Some(25),
184                    closure_capture_hints: false,
185                    closing_brace_hints_min_lines: Some(25),
186                    fields_to_resolve: InlayFieldsToResolve::empty(),
187                    range_exclusive_hints: false,
188                    minicore: MiniCore::default(),
189                },
190                file_id,
191                None,
192            )
193            .unwrap();
194        // hovers
195        let sema = hir::Semantics::new(self.db);
196        let root = sema.parse_guess_edition(file_id).syntax().clone();
197        let edition = sema
198            .attach_first_edition(file_id)
199            .map(|it| it.edition(self.db))
200            .unwrap_or(Edition::CURRENT);
201        let display_target = match sema.first_crate(file_id) {
202            Some(krate) => krate.to_display_target(sema.db),
203            None => return,
204        };
205        let tokens = root.descendants_with_tokens().filter_map(|it| match it {
206            syntax::NodeOrToken::Node(_) => None,
207            syntax::NodeOrToken::Token(it) => Some(it),
208        });
209        let hover_config = HoverConfig {
210            links_in_hover: true,
211            memory_layout: None,
212            documentation: true,
213            keywords: true,
214            format: crate::HoverDocFormat::Markdown,
215            max_trait_assoc_items_count: None,
216            max_fields_count: Some(5),
217            max_enum_variants_count: Some(5),
218            max_subst_ty_len: SubstTyLen::Unlimited,
219            show_drop_glue: true,
220            minicore: MiniCore::default(),
221        };
222        let tokens = tokens.filter(|token| {
223            matches!(
224                token.kind(),
225                IDENT | INT_NUMBER | LIFETIME_IDENT | T![self] | T![super] | T![crate] | T![Self]
226            )
227        });
228        let mut result = StaticIndexedFile { file_id, inlay_hints, folds, tokens: vec![] };
229
230        let mut add_token = |def: Definition, range: TextRange, scope_node: &SyntaxNode| {
231            let id = if let Some(it) = self.def_map.get(&def) {
232                *it
233            } else {
234                let it = self.tokens.insert(TokenStaticData {
235                    documentation: documentation_for_definition(&sema, def, scope_node),
236                    hover: Some(hover_for_definition(
237                        &sema,
238                        file_id,
239                        def,
240                        None,
241                        scope_node,
242                        None,
243                        false,
244                        &hover_config,
245                        edition,
246                        display_target,
247                    )),
248                    definition: def.try_to_nav(&sema).map(UpmappingResult::call_site).map(|it| {
249                        FileRange { file_id: it.file_id, range: it.focus_or_full_range() }
250                    }),
251                    references: vec![],
252                    moniker: current_crate.and_then(|cc| def_to_moniker(self.db, def, cc)),
253                    display_name: def
254                        .name(self.db)
255                        .map(|name| name.display(self.db, edition).to_string()),
256                    signature: Some(def.label(self.db, display_target)),
257                    kind: def_to_kind(self.db, def),
258                });
259                self.def_map.insert(def, it);
260                it
261            };
262            let token = self.tokens.get_mut(id).unwrap();
263            token.references.push(ReferenceData {
264                range: FileRange { range, file_id },
265                is_definition: match def.try_to_nav(&sema).map(UpmappingResult::call_site) {
266                    Some(it) => it.file_id == file_id && it.focus_or_full_range() == range,
267                    None => false,
268                },
269            });
270            result.tokens.push((range, id));
271        };
272
273        if let Some(module) = sema.file_to_module_def(file_id) {
274            let def = Definition::Module(module);
275            let range = root.text_range();
276            add_token(def, range, &root);
277        }
278
279        for token in tokens {
280            let range = token.text_range();
281            let node = token.parent().unwrap();
282            match hir::attach_db(self.db, || get_definitions(&sema, token.clone())) {
283                Some(it) => {
284                    for i in it {
285                        add_token(i, range, &node);
286                    }
287                }
288                None => continue,
289            };
290        }
291        self.files.push(result);
292    }
293
294    pub fn compute<'a>(
295        analysis: &'a Analysis,
296        vendored_libs_config: VendoredLibrariesConfig<'_>,
297    ) -> StaticIndex<'a> {
298        let db = &analysis.db;
299        hir::attach_db(db, || {
300            let work = all_modules(db).into_iter().filter(|module| {
301                let file_id = module.definition_source_file_id(db).original_file(db);
302                let source_root =
303                    db.file_source_root(file_id.file_id(&analysis.db)).source_root_id(db);
304                let source_root = db.source_root(source_root).source_root(db);
305                let is_vendored = match vendored_libs_config {
306                    VendoredLibrariesConfig::Included { workspace_root } => source_root
307                        .path_for_file(&file_id.file_id(&analysis.db))
308                        .is_some_and(|module_path| module_path.starts_with(workspace_root)),
309                    VendoredLibrariesConfig::Excluded => false,
310                };
311
312                !source_root.is_library || is_vendored
313            });
314            let mut this = StaticIndex {
315                files: vec![],
316                tokens: Default::default(),
317                analysis,
318                db,
319                def_map: Default::default(),
320            };
321            let mut visited_files = FxHashSet::default();
322            for module in work {
323                let file_id = module.definition_source_file_id(db).original_file(db);
324                if visited_files.contains(&file_id) {
325                    continue;
326                }
327                this.add_file(file_id.file_id(&analysis.db));
328                // mark the file
329                visited_files.insert(file_id);
330            }
331            this
332        })
333    }
334}
335
336#[cfg(test)]
337mod tests {
338    use crate::{StaticIndex, fixture};
339    use ide_db::{FileRange, FxHashMap, FxHashSet, base_db::VfsPath};
340    use syntax::TextSize;
341
342    use super::VendoredLibrariesConfig;
343
344    fn check_all_ranges(
345        #[rust_analyzer::rust_fixture] ra_fixture: &str,
346        vendored_libs_config: VendoredLibrariesConfig<'_>,
347    ) {
348        let (analysis, ranges) = fixture::annotations_without_marker(ra_fixture);
349        let s = StaticIndex::compute(&analysis, vendored_libs_config);
350        let mut range_set: FxHashSet<_> = ranges.iter().map(|it| it.0).collect();
351        for f in s.files {
352            for (range, _) in f.tokens {
353                if range.start() == TextSize::from(0) {
354                    // ignore whole file range corresponding to module definition
355                    continue;
356                }
357                let it = FileRange { file_id: f.file_id, range };
358                if !range_set.contains(&it) {
359                    panic!("additional range {it:?}");
360                }
361                range_set.remove(&it);
362            }
363        }
364        if !range_set.is_empty() {
365            panic!("unfound ranges {range_set:?}");
366        }
367    }
368
369    #[track_caller]
370    fn check_definitions(
371        #[rust_analyzer::rust_fixture] ra_fixture: &str,
372        vendored_libs_config: VendoredLibrariesConfig<'_>,
373    ) {
374        let (analysis, ranges) = fixture::annotations_without_marker(ra_fixture);
375        let s = StaticIndex::compute(&analysis, vendored_libs_config);
376        let mut range_set: FxHashSet<_> = ranges.iter().map(|it| it.0).collect();
377        for (_, t) in s.tokens.iter() {
378            if let Some(t) = t.definition {
379                if t.range.start() == TextSize::from(0) {
380                    // ignore definitions that are whole of file
381                    continue;
382                }
383                if !range_set.contains(&t) {
384                    panic!("additional definition {t:?}");
385                }
386                range_set.remove(&t);
387            }
388        }
389        if !range_set.is_empty() {
390            panic!("unfound definitions {range_set:?}");
391        }
392    }
393
394    #[track_caller]
395    fn check_references(
396        #[rust_analyzer::rust_fixture] ra_fixture: &str,
397        vendored_libs_config: VendoredLibrariesConfig<'_>,
398    ) {
399        let (analysis, ranges) = fixture::annotations_without_marker(ra_fixture);
400        let s = StaticIndex::compute(&analysis, vendored_libs_config);
401        let mut range_set: FxHashMap<_, i32> = ranges.iter().map(|it| (it.0, 0)).collect();
402
403        // Make sure that all references have at least one range. We use a HashMap instead of a
404        // a HashSet so that we can have more than one reference at the same range.
405        for (_, t) in s.tokens.iter() {
406            for r in &t.references {
407                if r.is_definition {
408                    continue;
409                }
410                if r.range.range.start() == TextSize::from(0) {
411                    // ignore whole file range corresponding to module definition
412                    continue;
413                }
414                match range_set.entry(r.range) {
415                    std::collections::hash_map::Entry::Occupied(mut entry) => {
416                        let count = entry.get_mut();
417                        *count += 1;
418                    }
419                    std::collections::hash_map::Entry::Vacant(_) => {
420                        panic!("additional reference {r:?}");
421                    }
422                }
423            }
424        }
425        for (range, count) in range_set.iter() {
426            if *count == 0 {
427                panic!("unfound reference {range:?}");
428            }
429        }
430    }
431
432    #[test]
433    fn field_initialization() {
434        check_references(
435            r#"
436struct Point {
437    x: f64,
438     //^^^
439    y: f64,
440     //^^^
441}
442    fn foo() {
443        let x = 5.;
444        let y = 10.;
445        let mut p = Point { x, y };
446                  //^^^^^   ^  ^
447        p.x = 9.;
448      //^ ^
449        p.y = 10.;
450      //^ ^
451    }
452"#,
453            VendoredLibrariesConfig::Included {
454                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
455            },
456        );
457    }
458
459    #[test]
460    fn struct_and_enum() {
461        check_all_ranges(
462            r#"
463struct Foo;
464     //^^^
465enum E { X(Foo) }
466   //^   ^ ^^^
467"#,
468            VendoredLibrariesConfig::Included {
469                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
470            },
471        );
472        check_definitions(
473            r#"
474struct Foo;
475     //^^^
476enum E { X(Foo) }
477   //^   ^
478"#,
479            VendoredLibrariesConfig::Included {
480                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
481            },
482        );
483
484        check_references(
485            r#"
486struct Foo;
487enum E { X(Foo) }
488   //      ^^^
489"#,
490            VendoredLibrariesConfig::Included {
491                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
492            },
493        );
494    }
495
496    #[test]
497    fn multi_crate() {
498        check_definitions(
499            r#"
500//- /workspace/main.rs crate:main deps:foo
501
502
503use foo::func;
504
505fn main() {
506 //^^^^
507    func();
508}
509//- /workspace/foo/lib.rs crate:foo
510
511pub func() {
512
513}
514"#,
515            VendoredLibrariesConfig::Included {
516                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
517            },
518        );
519    }
520
521    #[test]
522    fn vendored_crate() {
523        check_all_ranges(
524            r#"
525//- /workspace/main.rs crate:main deps:external,vendored
526struct Main(i32);
527     //^^^^ ^^^
528
529//- /external/lib.rs new_source_root:library crate:external@0.1.0,https://a.b/foo.git library
530struct ExternalLibrary(i32);
531
532//- /workspace/vendored/lib.rs new_source_root:library crate:vendored@0.1.0,https://a.b/bar.git library
533struct VendoredLibrary(i32);
534     //^^^^^^^^^^^^^^^ ^^^
535"#,
536            VendoredLibrariesConfig::Included {
537                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
538            },
539        );
540    }
541
542    #[test]
543    fn vendored_crate_excluded() {
544        check_all_ranges(
545            r#"
546//- /workspace/main.rs crate:main deps:external,vendored
547struct Main(i32);
548     //^^^^ ^^^
549
550//- /external/lib.rs new_source_root:library crate:external@0.1.0,https://a.b/foo.git library
551struct ExternalLibrary(i32);
552
553//- /workspace/vendored/lib.rs new_source_root:library crate:vendored@0.1.0,https://a.b/bar.git library
554struct VendoredLibrary(i32);
555"#,
556            VendoredLibrariesConfig::Excluded,
557        )
558    }
559
560    #[test]
561    fn derives() {
562        check_all_ranges(
563            r#"
564//- minicore:derive
565#[rustc_builtin_macro]
566//^^^^^^^^^^^^^^^^^^^
567pub macro Copy {}
568        //^^^^
569#[derive(Copy)]
570//^^^^^^ ^^^^
571struct Hello(i32);
572     //^^^^^ ^^^
573"#,
574            VendoredLibrariesConfig::Included {
575                workspace_root: &VfsPath::new_virtual_path("/workspace".to_owned()),
576            },
577        );
578    }
579}