ide/
lib.rs

1//! ide crate provides "ide-centric" APIs for the rust-analyzer. That is,
2//! it generally operates with files and text ranges, and returns results as
3//! Strings, suitable for displaying to the human.
4//!
5//! What powers this API are the `RootDatabase` struct, which defines a `salsa`
6//! database, and the `hir` crate, where majority of the analysis happens.
7//! However, IDE specific bits of the analysis (most notably completion) happen
8//! in this crate.
9
10// For proving that RootDatabase is RefUnwindSafe.
11
12#![cfg_attr(feature = "in-rust-tree", feature(rustc_private))]
13#![recursion_limit = "128"]
14
15#[cfg(test)]
16mod fixture;
17
18mod markup;
19mod navigation_target;
20
21mod annotations;
22mod call_hierarchy;
23mod child_modules;
24mod doc_links;
25mod expand_macro;
26mod extend_selection;
27mod fetch_crates;
28mod file_structure;
29mod folding_ranges;
30mod goto_declaration;
31mod goto_definition;
32mod goto_implementation;
33mod goto_type_definition;
34mod highlight_related;
35mod hover;
36mod inlay_hints;
37mod interpret;
38mod join_lines;
39mod markdown_remove;
40mod matching_brace;
41mod moniker;
42mod move_item;
43mod parent_module;
44mod references;
45mod rename;
46mod runnables;
47mod signature_help;
48mod ssr;
49mod static_index;
50mod status;
51mod syntax_highlighting;
52mod test_explorer;
53mod typing;
54mod view_crate_graph;
55mod view_hir;
56mod view_item_tree;
57mod view_memory_layout;
58mod view_mir;
59mod view_syntax_tree;
60
61use std::panic::{AssertUnwindSafe, UnwindSafe};
62
63use cfg::CfgOptions;
64use fetch_crates::CrateInfo;
65use hir::{ChangeWithProcMacros, EditionedFileId, crate_def_map, sym};
66use ide_db::ra_fixture::RaFixtureAnalysis;
67use ide_db::{
68    FxHashMap, FxIndexSet, LineIndexDatabase,
69    base_db::{
70        CrateOrigin, CrateWorkspaceData, Env, FileSet, RootQueryDb, SourceDatabase, VfsPath,
71        salsa::{Cancelled, Database},
72    },
73    prime_caches, symbol_index,
74};
75use macros::UpmapFromRaFixture;
76use syntax::{AstNode, SourceFile, ast};
77use triomphe::Arc;
78use view_memory_layout::{RecursiveMemoryLayout, view_memory_layout};
79
80use crate::navigation_target::ToNav;
81
82pub use crate::{
83    annotations::{Annotation, AnnotationConfig, AnnotationKind, AnnotationLocation},
84    call_hierarchy::{CallHierarchyConfig, CallItem},
85    expand_macro::ExpandedMacro,
86    file_structure::{FileStructureConfig, StructureNode, StructureNodeKind},
87    folding_ranges::{Fold, FoldKind},
88    goto_definition::GotoDefinitionConfig,
89    goto_implementation::GotoImplementationConfig,
90    highlight_related::{HighlightRelatedConfig, HighlightedRange},
91    hover::{
92        HoverAction, HoverConfig, HoverDocFormat, HoverGotoTypeData, HoverResult,
93        MemoryLayoutHoverConfig, MemoryLayoutHoverRenderKind, SubstTyLen,
94    },
95    inlay_hints::{
96        AdjustmentHints, AdjustmentHintsMode, ClosureReturnTypeHints, DiscriminantHints,
97        GenericParameterHints, InlayFieldsToResolve, InlayHint, InlayHintLabel, InlayHintLabelPart,
98        InlayHintPosition, InlayHintsConfig, InlayKind, InlayTooltip, LazyProperty,
99        LifetimeElisionHints,
100    },
101    join_lines::JoinLinesConfig,
102    markup::Markup,
103    moniker::{
104        Moniker, MonikerDescriptorKind, MonikerIdentifier, MonikerKind, MonikerResult,
105        PackageInformation, SymbolInformationKind,
106    },
107    move_item::Direction,
108    navigation_target::{NavigationTarget, TryToNav, UpmappingResult},
109    references::{FindAllRefsConfig, ReferenceSearchResult},
110    rename::{RenameConfig, RenameError},
111    runnables::{Runnable, RunnableKind, TestId, UpdateTest},
112    signature_help::SignatureHelp,
113    static_index::{
114        StaticIndex, StaticIndexedFile, TokenId, TokenStaticData, VendoredLibrariesConfig,
115    },
116    syntax_highlighting::{
117        HighlightConfig, HlRange,
118        tags::{Highlight, HlMod, HlMods, HlOperator, HlPunct, HlTag},
119    },
120    test_explorer::{TestItem, TestItemKind},
121};
122pub use hir::Semantics;
123pub use ide_assists::{
124    Assist, AssistConfig, AssistId, AssistKind, AssistResolveStrategy, SingleResolve,
125};
126pub use ide_completion::{
127    CallableSnippets, CompletionConfig, CompletionFieldsToResolve, CompletionItem,
128    CompletionItemKind, CompletionItemRefMode, CompletionRelevance, Snippet, SnippetScope,
129};
130pub use ide_db::{
131    FileId, FilePosition, FileRange, RootDatabase, Severity, SymbolKind,
132    assists::ExprFillDefaultMode,
133    base_db::{Crate, CrateGraphBuilder, FileChange, SourceRoot, SourceRootId},
134    documentation::Documentation,
135    label::Label,
136    line_index::{LineCol, LineIndex},
137    prime_caches::ParallelPrimeCachesProgress,
138    ra_fixture::RaFixtureConfig,
139    search::{ReferenceCategory, SearchScope},
140    source_change::{FileSystemEdit, SnippetEdit, SourceChange},
141    symbol_index::Query,
142    text_edit::{Indel, TextEdit},
143};
144pub use ide_diagnostics::{Diagnostic, DiagnosticCode, DiagnosticsConfig};
145pub use ide_ssr::SsrError;
146pub use span::Edition;
147pub use syntax::{TextRange, TextSize};
148
149pub type Cancellable<T> = Result<T, Cancelled>;
150
151/// Info associated with a text range.
152#[derive(Debug, UpmapFromRaFixture)]
153pub struct RangeInfo<T> {
154    pub range: TextRange,
155    pub info: T,
156}
157
158impl<T> RangeInfo<T> {
159    pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
160        RangeInfo { range, info }
161    }
162}
163
164/// `AnalysisHost` stores the current state of the world.
165#[derive(Debug)]
166pub struct AnalysisHost {
167    db: RootDatabase,
168}
169
170impl AnalysisHost {
171    pub fn new(lru_capacity: Option<u16>) -> AnalysisHost {
172        AnalysisHost { db: RootDatabase::new(lru_capacity) }
173    }
174
175    pub fn with_database(db: RootDatabase) -> AnalysisHost {
176        AnalysisHost { db }
177    }
178
179    pub fn update_lru_capacity(&mut self, lru_capacity: Option<u16>) {
180        self.db.update_base_query_lru_capacities(lru_capacity);
181    }
182
183    pub fn update_lru_capacities(&mut self, lru_capacities: &FxHashMap<Box<str>, u16>) {
184        self.db.update_lru_capacities(lru_capacities);
185    }
186
187    /// Returns a snapshot of the current state, which you can query for
188    /// semantic information.
189    pub fn analysis(&self) -> Analysis {
190        Analysis { db: self.db.clone() }
191    }
192
193    /// Applies changes to the current state of the world. If there are
194    /// outstanding snapshots, they will be canceled.
195    pub fn apply_change(&mut self, change: ChangeWithProcMacros) {
196        self.db.apply_change(change);
197    }
198
199    /// NB: this clears the database
200    pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes, usize)> {
201        self.db.per_query_memory_usage()
202    }
203    pub fn trigger_cancellation(&mut self) {
204        self.db.trigger_cancellation();
205    }
206    pub fn trigger_garbage_collection(&mut self) {
207        self.db.trigger_lru_eviction();
208        // SAFETY: `trigger_lru_eviction` triggers cancellation, so all running queries were canceled.
209        unsafe { hir::collect_ty_garbage() };
210    }
211    pub fn raw_database(&self) -> &RootDatabase {
212        &self.db
213    }
214    pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
215        &mut self.db
216    }
217}
218
219impl Default for AnalysisHost {
220    fn default() -> AnalysisHost {
221        AnalysisHost::new(None)
222    }
223}
224
225/// Analysis is a snapshot of a world state at a moment in time. It is the main
226/// entry point for asking semantic information about the world. When the world
227/// state is advanced using `AnalysisHost::apply_change` method, all existing
228/// `Analysis` are canceled (most method return `Err(Canceled)`).
229#[derive(Debug)]
230pub struct Analysis {
231    db: RootDatabase,
232}
233
234// As a general design guideline, `Analysis` API are intended to be independent
235// from the language server protocol. That is, when exposing some functionality
236// we should think in terms of "what API makes most sense" and not in terms of
237// "what types LSP uses". Although currently LSP is the only consumer of the
238// API, the API should in theory be usable as a library, or via a different
239// protocol.
240impl Analysis {
241    // Creates an analysis instance for a single file, without any external
242    // dependencies, stdlib support or ability to apply changes. See
243    // `AnalysisHost` for creating a fully-featured analysis.
244    pub fn from_single_file(text: String) -> (Analysis, FileId) {
245        let mut host = AnalysisHost::default();
246        let file_id = FileId::from_raw(0);
247        let mut file_set = FileSet::default();
248        file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_owned()));
249        let source_root = SourceRoot::new_local(file_set);
250
251        let mut change = ChangeWithProcMacros::default();
252        change.set_roots(vec![source_root]);
253        let mut crate_graph = CrateGraphBuilder::default();
254        // FIXME: cfg options
255        // Default to enable test for single file.
256        let mut cfg_options = CfgOptions::default();
257
258        // FIXME: This is less than ideal
259        let proc_macro_cwd = Arc::new(
260            TryFrom::try_from(&*std::env::current_dir().unwrap().as_path().to_string_lossy())
261                .unwrap(),
262        );
263        let crate_attrs = Vec::new();
264        cfg_options.insert_atom(sym::test);
265        crate_graph.add_crate_root(
266            file_id,
267            Edition::CURRENT,
268            None,
269            None,
270            cfg_options,
271            None,
272            Env::default(),
273            CrateOrigin::Local { repo: None, name: None },
274            crate_attrs,
275            false,
276            proc_macro_cwd,
277            Arc::new(CrateWorkspaceData {
278                target: Err("fixture has no layout".into()),
279                toolchain: None,
280            }),
281        );
282        change.change_file(file_id, Some(text));
283        change.set_crate_graph(crate_graph);
284
285        host.apply_change(change);
286        (host.analysis(), file_id)
287    }
288
289    pub(crate) fn from_ra_fixture(
290        sema: &Semantics<'_, RootDatabase>,
291        literal: ast::String,
292        expanded: &ast::String,
293        config: &RaFixtureConfig<'_>,
294    ) -> Option<(Analysis, RaFixtureAnalysis)> {
295        Self::from_ra_fixture_with_on_cursor(sema, literal, expanded, config, &mut |_| {})
296    }
297
298    /// Like [`Analysis::from_ra_fixture()`], but also calls `on_cursor` with the cursor position.
299    pub(crate) fn from_ra_fixture_with_on_cursor(
300        sema: &Semantics<'_, RootDatabase>,
301        literal: ast::String,
302        expanded: &ast::String,
303        config: &RaFixtureConfig<'_>,
304        on_cursor: &mut dyn FnMut(TextRange),
305    ) -> Option<(Analysis, RaFixtureAnalysis)> {
306        let analysis =
307            RaFixtureAnalysis::analyze_ra_fixture(sema, literal, expanded, config, on_cursor)?;
308        Some((Analysis { db: analysis.db.clone() }, analysis))
309    }
310
311    /// Debug info about the current state of the analysis.
312    pub fn status(&self, file_id: Option<FileId>) -> Cancellable<String> {
313        self.with_db(|db| status::status(db, file_id))
314    }
315
316    pub fn source_root_id(&self, file_id: FileId) -> Cancellable<SourceRootId> {
317        self.with_db(|db| db.file_source_root(file_id).source_root_id(db))
318    }
319
320    pub fn is_local_source_root(&self, source_root_id: SourceRootId) -> Cancellable<bool> {
321        self.with_db(|db| {
322            let sr = db.source_root(source_root_id).source_root(db);
323            !sr.is_library
324        })
325    }
326
327    pub fn parallel_prime_caches<F>(&self, num_worker_threads: usize, cb: F) -> Cancellable<()>
328    where
329        F: Fn(ParallelPrimeCachesProgress) + Sync + std::panic::UnwindSafe,
330    {
331        self.with_db(move |db| prime_caches::parallel_prime_caches(db, num_worker_threads, &cb))
332    }
333
334    /// Gets the text of the source file.
335    pub fn file_text(&self, file_id: FileId) -> Cancellable<Arc<str>> {
336        self.with_db(|db| SourceDatabase::file_text(db, file_id).text(db).clone())
337    }
338
339    /// Gets the syntax tree of the file.
340    pub fn parse(&self, file_id: FileId) -> Cancellable<SourceFile> {
341        // FIXME edition
342        self.with_db(|db| {
343            let editioned_file_id_wrapper = EditionedFileId::current_edition(&self.db, file_id);
344
345            db.parse(editioned_file_id_wrapper).tree()
346        })
347    }
348
349    /// Returns true if this file belongs to an immutable library.
350    pub fn is_library_file(&self, file_id: FileId) -> Cancellable<bool> {
351        self.with_db(|db| {
352            let source_root = db.file_source_root(file_id).source_root_id(db);
353            db.source_root(source_root).source_root(db).is_library
354        })
355    }
356
357    /// Gets the file's `LineIndex`: data structure to convert between absolute
358    /// offsets and line/column representation.
359    pub fn file_line_index(&self, file_id: FileId) -> Cancellable<Arc<LineIndex>> {
360        self.with_db(|db| db.line_index(file_id))
361    }
362
363    /// Selects the next syntactic nodes encompassing the range.
364    pub fn extend_selection(&self, frange: FileRange) -> Cancellable<TextRange> {
365        self.with_db(|db| extend_selection::extend_selection(db, frange))
366    }
367
368    /// Returns position of the matching brace (all types of braces are
369    /// supported).
370    pub fn matching_brace(&self, position: FilePosition) -> Cancellable<Option<TextSize>> {
371        self.with_db(|db| {
372            let file_id = EditionedFileId::current_edition(&self.db, position.file_id);
373            let parse = db.parse(file_id);
374            let file = parse.tree();
375            matching_brace::matching_brace(&file, position.offset)
376        })
377    }
378
379    pub fn view_syntax_tree(&self, file_id: FileId) -> Cancellable<String> {
380        self.with_db(|db| view_syntax_tree::view_syntax_tree(db, file_id))
381    }
382
383    pub fn view_hir(&self, position: FilePosition) -> Cancellable<String> {
384        self.with_db(|db| view_hir::view_hir(db, position))
385    }
386
387    pub fn view_mir(&self, position: FilePosition) -> Cancellable<String> {
388        self.with_db(|db| view_mir::view_mir(db, position))
389    }
390
391    pub fn interpret_function(&self, position: FilePosition) -> Cancellable<String> {
392        self.with_db(|db| interpret::interpret(db, position))
393    }
394
395    pub fn view_item_tree(&self, file_id: FileId) -> Cancellable<String> {
396        self.with_db(|db| view_item_tree::view_item_tree(db, file_id))
397    }
398
399    pub fn discover_test_roots(&self) -> Cancellable<Vec<TestItem>> {
400        self.with_db(test_explorer::discover_test_roots)
401    }
402
403    pub fn discover_tests_in_crate_by_test_id(&self, crate_id: &str) -> Cancellable<Vec<TestItem>> {
404        self.with_db(|db| test_explorer::discover_tests_in_crate_by_test_id(db, crate_id))
405    }
406
407    pub fn discover_tests_in_crate(&self, crate_id: Crate) -> Cancellable<Vec<TestItem>> {
408        self.with_db(|db| test_explorer::discover_tests_in_crate(db, crate_id))
409    }
410
411    pub fn discover_tests_in_file(&self, file_id: FileId) -> Cancellable<Vec<TestItem>> {
412        self.with_db(|db| test_explorer::discover_tests_in_file(db, file_id))
413    }
414
415    /// Renders the crate graph to GraphViz "dot" syntax.
416    pub fn view_crate_graph(&self, full: bool) -> Cancellable<Result<String, String>> {
417        self.with_db(|db| view_crate_graph::view_crate_graph(db, full))
418    }
419
420    pub fn fetch_crates(&self) -> Cancellable<FxIndexSet<CrateInfo>> {
421        self.with_db(fetch_crates::fetch_crates)
422    }
423
424    pub fn expand_macro(&self, position: FilePosition) -> Cancellable<Option<ExpandedMacro>> {
425        self.with_db(|db| expand_macro::expand_macro(db, position))
426    }
427
428    /// Returns an edit to remove all newlines in the range, cleaning up minor
429    /// stuff like trailing commas.
430    pub fn join_lines(&self, config: &JoinLinesConfig, frange: FileRange) -> Cancellable<TextEdit> {
431        self.with_db(|db| {
432            let editioned_file_id_wrapper =
433                EditionedFileId::current_edition(&self.db, frange.file_id);
434            let parse = db.parse(editioned_file_id_wrapper);
435            join_lines::join_lines(config, &parse.tree(), frange.range)
436        })
437    }
438
439    /// Returns an edit which should be applied when opening a new line, fixing
440    /// up minor stuff like continuing the comment.
441    /// The edit will be a snippet (with `$0`).
442    pub fn on_enter(&self, position: FilePosition) -> Cancellable<Option<TextEdit>> {
443        self.with_db(|db| typing::on_enter(db, position))
444    }
445
446    pub const SUPPORTED_TRIGGER_CHARS: &[char] = typing::TRIGGER_CHARS;
447
448    /// Returns an edit which should be applied after a character was typed.
449    ///
450    /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
451    /// automatically.
452    pub fn on_char_typed(
453        &self,
454        position: FilePosition,
455        char_typed: char,
456    ) -> Cancellable<Option<SourceChange>> {
457        // Fast path to not even parse the file.
458        if !typing::TRIGGER_CHARS.contains(&char_typed) {
459            return Ok(None);
460        }
461
462        self.with_db(|db| typing::on_char_typed(db, position, char_typed))
463    }
464
465    /// Returns a tree representation of symbols in the file. Useful to draw a
466    /// file outline.
467    pub fn file_structure(
468        &self,
469        config: &FileStructureConfig,
470        file_id: FileId,
471    ) -> Cancellable<Vec<StructureNode>> {
472        // FIXME: Edition
473        self.with_db(|db| {
474            let editioned_file_id_wrapper = EditionedFileId::current_edition(&self.db, file_id);
475            let source_file = db.parse(editioned_file_id_wrapper).tree();
476            file_structure::file_structure(&source_file, config)
477        })
478    }
479
480    /// Returns a list of the places in the file where type hints can be displayed.
481    pub fn inlay_hints(
482        &self,
483        config: &InlayHintsConfig<'_>,
484        file_id: FileId,
485        range: Option<TextRange>,
486    ) -> Cancellable<Vec<InlayHint>> {
487        self.with_db(|db| inlay_hints::inlay_hints(db, file_id, range, config))
488    }
489    pub fn inlay_hints_resolve(
490        &self,
491        config: &InlayHintsConfig<'_>,
492        file_id: FileId,
493        resolve_range: TextRange,
494        hash: u64,
495        hasher: impl Fn(&InlayHint) -> u64 + Send + UnwindSafe,
496    ) -> Cancellable<Option<InlayHint>> {
497        self.with_db(|db| {
498            inlay_hints::inlay_hints_resolve(db, file_id, resolve_range, hash, config, hasher)
499        })
500    }
501
502    /// Returns the set of folding ranges.
503    pub fn folding_ranges(&self, file_id: FileId) -> Cancellable<Vec<Fold>> {
504        self.with_db(|db| {
505            let editioned_file_id_wrapper = EditionedFileId::current_edition(&self.db, file_id);
506
507            folding_ranges::folding_ranges(&db.parse(editioned_file_id_wrapper).tree())
508        })
509    }
510
511    /// Fuzzy searches for a symbol.
512    pub fn symbol_search(&self, query: Query, limit: usize) -> Cancellable<Vec<NavigationTarget>> {
513        // `world_symbols` currently clones the database to run stuff in parallel, which will make any query panic
514        // if we were to attach it here.
515        Cancelled::catch(|| {
516            let symbols = symbol_index::world_symbols(&self.db, query);
517            hir::attach_db(&self.db, || {
518                symbols
519                    .into_iter()
520                    .filter_map(|s| s.try_to_nav(&Semantics::new(&self.db)))
521                    .take(limit)
522                    .map(UpmappingResult::call_site)
523                    .collect::<Vec<_>>()
524            })
525        })
526    }
527
528    /// Returns the definitions from the symbol at `position`.
529    pub fn goto_definition(
530        &self,
531        position: FilePosition,
532        config: &GotoDefinitionConfig<'_>,
533    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
534        self.with_db(|db| goto_definition::goto_definition(db, position, config))
535    }
536
537    /// Returns the declaration from the symbol at `position`.
538    pub fn goto_declaration(
539        &self,
540        position: FilePosition,
541        config: &GotoDefinitionConfig<'_>,
542    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
543        self.with_db(|db| goto_declaration::goto_declaration(db, position, config))
544    }
545
546    /// Returns the impls from the symbol at `position`.
547    pub fn goto_implementation(
548        &self,
549        config: &GotoImplementationConfig,
550        position: FilePosition,
551    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
552        self.with_db(|db| goto_implementation::goto_implementation(db, config, position))
553    }
554
555    /// Returns the type definitions for the symbol at `position`.
556    pub fn goto_type_definition(
557        &self,
558        position: FilePosition,
559    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
560        self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
561    }
562
563    pub fn find_all_refs(
564        &self,
565        position: FilePosition,
566        config: &FindAllRefsConfig<'_>,
567    ) -> Cancellable<Option<Vec<ReferenceSearchResult>>> {
568        let config = AssertUnwindSafe(config);
569        self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, &config))
570    }
571
572    /// Returns a short text describing element at position.
573    pub fn hover(
574        &self,
575        config: &HoverConfig<'_>,
576        range: FileRange,
577    ) -> Cancellable<Option<RangeInfo<HoverResult>>> {
578        self.with_db(|db| hover::hover(db, range, config))
579    }
580
581    /// Returns moniker of symbol at position.
582    pub fn moniker(
583        &self,
584        position: FilePosition,
585    ) -> Cancellable<Option<RangeInfo<Vec<moniker::MonikerResult>>>> {
586        self.with_db(|db| moniker::moniker(db, position))
587    }
588
589    /// Returns URL(s) for the documentation of the symbol under the cursor.
590    /// # Arguments
591    /// * `position` - Position in the file.
592    /// * `target_dir` - Directory where the build output is stored.
593    pub fn external_docs(
594        &self,
595        position: FilePosition,
596        target_dir: Option<&str>,
597        sysroot: Option<&str>,
598    ) -> Cancellable<doc_links::DocumentationLinks> {
599        self.with_db(|db| {
600            doc_links::external_docs(db, position, target_dir, sysroot).unwrap_or_default()
601        })
602    }
603
604    /// Computes parameter information at the given position.
605    pub fn signature_help(&self, position: FilePosition) -> Cancellable<Option<SignatureHelp>> {
606        self.with_db(|db| signature_help::signature_help(db, position))
607    }
608
609    /// Computes call hierarchy candidates for the given file position.
610    pub fn call_hierarchy(
611        &self,
612        position: FilePosition,
613        config: &CallHierarchyConfig<'_>,
614    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
615        self.with_db(|db| call_hierarchy::call_hierarchy(db, position, config))
616    }
617
618    /// Computes incoming calls for the given file position.
619    pub fn incoming_calls(
620        &self,
621        config: &CallHierarchyConfig<'_>,
622        position: FilePosition,
623    ) -> Cancellable<Option<Vec<CallItem>>> {
624        self.with_db(|db| call_hierarchy::incoming_calls(db, config, position))
625    }
626
627    /// Computes outgoing calls for the given file position.
628    pub fn outgoing_calls(
629        &self,
630        config: &CallHierarchyConfig<'_>,
631        position: FilePosition,
632    ) -> Cancellable<Option<Vec<CallItem>>> {
633        self.with_db(|db| call_hierarchy::outgoing_calls(db, config, position))
634    }
635
636    /// Returns a `mod name;` declaration which created the current module.
637    pub fn parent_module(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
638        self.with_db(|db| parent_module::parent_module(db, position))
639    }
640
641    /// Returns vec of `mod name;` declaration which are created by the current module.
642    pub fn child_modules(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
643        self.with_db(|db| child_modules::child_modules(db, position))
644    }
645
646    /// Returns crates that this file belongs to.
647    pub fn crates_for(&self, file_id: FileId) -> Cancellable<Vec<Crate>> {
648        self.with_db(|db| parent_module::crates_for(db, file_id))
649    }
650
651    /// Returns crates that this file belongs to.
652    pub fn transitive_rev_deps(&self, crate_id: Crate) -> Cancellable<Vec<Crate>> {
653        self.with_db(|db| Vec::from_iter(crate_id.transitive_rev_deps(db)))
654    }
655
656    /// Returns crates that this file *might* belong to.
657    pub fn relevant_crates_for(&self, file_id: FileId) -> Cancellable<Vec<Crate>> {
658        self.with_db(|db| db.relevant_crates(file_id).iter().copied().collect())
659    }
660
661    /// Returns the edition of the given crate.
662    pub fn crate_edition(&self, crate_id: Crate) -> Cancellable<Edition> {
663        self.with_db(|db| crate_id.data(db).edition)
664    }
665
666    /// Returns whether the given crate is a proc macro.
667    pub fn is_proc_macro_crate(&self, crate_id: Crate) -> Cancellable<bool> {
668        self.with_db(|db| crate_id.data(db).is_proc_macro)
669    }
670
671    /// Returns true if this crate has `no_std` or `no_core` specified.
672    pub fn is_crate_no_std(&self, crate_id: Crate) -> Cancellable<bool> {
673        self.with_db(|db| crate_def_map(db, crate_id).is_no_std())
674    }
675
676    /// Returns the root file of the given crate.
677    pub fn crate_root(&self, crate_id: Crate) -> Cancellable<FileId> {
678        self.with_db(|db| crate_id.data(db).root_file_id)
679    }
680
681    /// Returns the set of possible targets to run for the current file.
682    pub fn runnables(&self, file_id: FileId) -> Cancellable<Vec<Runnable>> {
683        self.with_db(|db| runnables::runnables(db, file_id))
684    }
685
686    /// Returns the set of tests for the given file position.
687    pub fn related_tests(
688        &self,
689        position: FilePosition,
690        search_scope: Option<SearchScope>,
691    ) -> Cancellable<Vec<Runnable>> {
692        let search_scope = AssertUnwindSafe(search_scope);
693        self.with_db(|db| {
694            let _ = &search_scope;
695            runnables::related_tests(db, position, search_scope.0)
696        })
697    }
698
699    /// Computes all ranges to highlight for a given item in a file.
700    pub fn highlight_related(
701        &self,
702        config: HighlightRelatedConfig,
703        position: FilePosition,
704    ) -> Cancellable<Option<Vec<HighlightedRange>>> {
705        self.with_db(|db| {
706            highlight_related::highlight_related(&Semantics::new(db), config, position)
707        })
708    }
709
710    /// Computes syntax highlighting for the given file
711    pub fn highlight(
712        &self,
713        highlight_config: HighlightConfig<'_>,
714        file_id: FileId,
715    ) -> Cancellable<Vec<HlRange>> {
716        self.with_db(|db| syntax_highlighting::highlight(db, &highlight_config, file_id, None))
717    }
718
719    /// Computes syntax highlighting for the given file range.
720    pub fn highlight_range(
721        &self,
722        highlight_config: HighlightConfig<'_>,
723        frange: FileRange,
724    ) -> Cancellable<Vec<HlRange>> {
725        self.with_db(|db| {
726            syntax_highlighting::highlight(
727                db,
728                &highlight_config,
729                frange.file_id,
730                Some(frange.range),
731            )
732        })
733    }
734
735    /// Computes syntax highlighting for the given file.
736    pub fn highlight_as_html_with_config(
737        &self,
738        config: HighlightConfig<'_>,
739        file_id: FileId,
740        rainbow: bool,
741    ) -> Cancellable<String> {
742        self.with_db(|db| {
743            syntax_highlighting::highlight_as_html_with_config(db, &config, file_id, rainbow)
744        })
745    }
746
747    /// Computes syntax highlighting for the given file.
748    pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancellable<String> {
749        self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
750    }
751
752    /// Computes completions at the given position.
753    pub fn completions(
754        &self,
755        config: &CompletionConfig<'_>,
756        position: FilePosition,
757        trigger_character: Option<char>,
758    ) -> Cancellable<Option<Vec<CompletionItem>>> {
759        self.with_db(|db| ide_completion::completions(db, config, position, trigger_character))
760    }
761
762    /// Resolves additional completion data at the position given.
763    pub fn resolve_completion_edits(
764        &self,
765        config: &CompletionConfig<'_>,
766        position: FilePosition,
767        imports: impl IntoIterator<Item = String> + std::panic::UnwindSafe,
768    ) -> Cancellable<Vec<TextEdit>> {
769        Ok(self
770            .with_db(|db| ide_completion::resolve_completion_edits(db, config, position, imports))?
771            .unwrap_or_default())
772    }
773
774    /// Computes the set of parser level diagnostics for the given file.
775    pub fn syntax_diagnostics(
776        &self,
777        config: &DiagnosticsConfig,
778        file_id: FileId,
779    ) -> Cancellable<Vec<Diagnostic>> {
780        self.with_db(|db| ide_diagnostics::syntax_diagnostics(db, config, file_id))
781    }
782
783    /// Computes the set of semantic diagnostics for the given file.
784    pub fn semantic_diagnostics(
785        &self,
786        config: &DiagnosticsConfig,
787        resolve: AssistResolveStrategy,
788        file_id: FileId,
789    ) -> Cancellable<Vec<Diagnostic>> {
790        self.with_db(|db| ide_diagnostics::semantic_diagnostics(db, config, &resolve, file_id))
791    }
792
793    /// Computes the set of both syntax and semantic diagnostics for the given file.
794    pub fn full_diagnostics(
795        &self,
796        config: &DiagnosticsConfig,
797        resolve: AssistResolveStrategy,
798        file_id: FileId,
799    ) -> Cancellable<Vec<Diagnostic>> {
800        self.with_db(|db| ide_diagnostics::full_diagnostics(db, config, &resolve, file_id))
801    }
802
803    /// Convenience function to return assists + quick fixes for diagnostics
804    pub fn assists_with_fixes(
805        &self,
806        assist_config: &AssistConfig,
807        diagnostics_config: &DiagnosticsConfig,
808        resolve: AssistResolveStrategy,
809        frange: FileRange,
810    ) -> Cancellable<Vec<Assist>> {
811        let include_fixes = match &assist_config.allowed {
812            Some(it) => it.contains(&AssistKind::QuickFix),
813            None => true,
814        };
815
816        self.with_db(|db| {
817            let diagnostic_assists = if diagnostics_config.enabled && include_fixes {
818                ide_diagnostics::full_diagnostics(db, diagnostics_config, &resolve, frange.file_id)
819                    .into_iter()
820                    .flat_map(|it| it.fixes.unwrap_or_default())
821                    .filter(|it| it.target.intersect(frange.range).is_some())
822                    .collect()
823            } else {
824                Vec::new()
825            };
826            let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
827            let assists = ide_assists::assists(db, assist_config, resolve, frange);
828
829            let mut res = diagnostic_assists;
830            res.extend(ssr_assists);
831            res.extend(assists);
832
833            res
834        })
835    }
836
837    /// Returns the edit required to rename reference at the position to the new
838    /// name.
839    pub fn rename(
840        &self,
841        position: FilePosition,
842        new_name: &str,
843        config: &RenameConfig,
844    ) -> Cancellable<Result<SourceChange, RenameError>> {
845        self.with_db(|db| rename::rename(db, position, new_name, config))
846    }
847
848    pub fn prepare_rename(
849        &self,
850        position: FilePosition,
851    ) -> Cancellable<Result<RangeInfo<()>, RenameError>> {
852        self.with_db(|db| rename::prepare_rename(db, position))
853    }
854
855    pub fn will_rename_file(
856        &self,
857        file_id: FileId,
858        new_name_stem: &str,
859        config: &RenameConfig,
860    ) -> Cancellable<Option<SourceChange>> {
861        self.with_db(|db| rename::will_rename_file(db, file_id, new_name_stem, config))
862    }
863
864    pub fn structural_search_replace(
865        &self,
866        query: &str,
867        parse_only: bool,
868        resolve_context: FilePosition,
869        selections: Vec<FileRange>,
870    ) -> Cancellable<Result<SourceChange, SsrError>> {
871        self.with_db(|db| {
872            let rule: ide_ssr::SsrRule = query.parse()?;
873            let mut match_finder =
874                ide_ssr::MatchFinder::in_context(db, resolve_context, selections)?;
875            match_finder.add_rule(rule)?;
876            let edits = if parse_only { Default::default() } else { match_finder.edits() };
877            Ok(SourceChange::from_iter(edits))
878        })
879    }
880
881    pub fn annotations(
882        &self,
883        config: &AnnotationConfig<'_>,
884        file_id: FileId,
885    ) -> Cancellable<Vec<Annotation>> {
886        self.with_db(|db| annotations::annotations(db, config, file_id))
887    }
888
889    pub fn resolve_annotation(
890        &self,
891        config: &AnnotationConfig<'_>,
892        annotation: Annotation,
893    ) -> Cancellable<Annotation> {
894        self.with_db(|db| annotations::resolve_annotation(db, config, annotation))
895    }
896
897    pub fn move_item(
898        &self,
899        range: FileRange,
900        direction: Direction,
901    ) -> Cancellable<Option<TextEdit>> {
902        self.with_db(|db| move_item::move_item(db, range, direction))
903    }
904
905    pub fn get_recursive_memory_layout(
906        &self,
907        position: FilePosition,
908    ) -> Cancellable<Option<RecursiveMemoryLayout>> {
909        self.with_db(|db| view_memory_layout(db, position))
910    }
911
912    pub fn get_failed_obligations(&self, offset: TextSize, file_id: FileId) -> Cancellable<String> {
913        self.with_db(|db| {
914            let sema = Semantics::new(db);
915            let source_file = sema.parse_guess_edition(file_id);
916
917            let Some(token) = source_file.syntax().token_at_offset(offset).next() else {
918                return String::new();
919            };
920            sema.get_failed_obligations(token).unwrap_or_default()
921        })
922    }
923
924    pub fn editioned_file_id_to_vfs(&self, file_id: hir::EditionedFileId) -> FileId {
925        file_id.file_id(&self.db)
926    }
927
928    /// Performs an operation on the database that may be canceled.
929    ///
930    /// rust-analyzer needs to be able to answer semantic questions about the
931    /// code while the code is being modified. A common problem is that a
932    /// long-running query is being calculated when a new change arrives.
933    ///
934    /// We can't just apply the change immediately: this will cause the pending
935    /// query to see inconsistent state (it will observe an absence of
936    /// repeatable read). So what we do is we **cancel** all pending queries
937    /// before applying the change.
938    ///
939    /// Salsa implements cancellation by unwinding with a special value and
940    /// catching it on the API boundary.
941    fn with_db<F, T>(&self, f: F) -> Cancellable<T>
942    where
943        F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
944    {
945        // We use `attach_db_allow_change()` and not `attach_db()` because fixture injection can change the database.
946        hir::attach_db_allow_change(&self.db, || Cancelled::catch(|| f(&self.db)))
947    }
948}
949
950#[test]
951fn analysis_is_send() {
952    fn is_send<T: Send>() {}
953    is_send::<Analysis>();
954}