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::{
67    FxHashMap, FxIndexSet, LineIndexDatabase,
68    base_db::{
69        CrateOrigin, CrateWorkspaceData, Env, FileSet, RootQueryDb, SourceDatabase, VfsPath,
70        salsa::{Cancelled, Database},
71    },
72    prime_caches, symbol_index,
73};
74use ide_db::{MiniCore, ra_fixture::RaFixtureAnalysis};
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    search::{ReferenceCategory, SearchScope},
139    source_change::{FileSystemEdit, SnippetEdit, SourceChange},
140    symbol_index::Query,
141    text_edit::{Indel, TextEdit},
142};
143pub use ide_diagnostics::{Diagnostic, DiagnosticCode, DiagnosticsConfig};
144pub use ide_ssr::SsrError;
145pub use span::Edition;
146pub use syntax::{TextRange, TextSize};
147
148pub type Cancellable<T> = Result<T, Cancelled>;
149
150/// Info associated with a text range.
151#[derive(Debug, UpmapFromRaFixture)]
152pub struct RangeInfo<T> {
153    pub range: TextRange,
154    pub info: T,
155}
156
157impl<T> RangeInfo<T> {
158    pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
159        RangeInfo { range, info }
160    }
161}
162
163/// `AnalysisHost` stores the current state of the world.
164#[derive(Debug)]
165pub struct AnalysisHost {
166    db: RootDatabase,
167}
168
169impl AnalysisHost {
170    pub fn new(lru_capacity: Option<u16>) -> AnalysisHost {
171        AnalysisHost { db: RootDatabase::new(lru_capacity) }
172    }
173
174    pub fn with_database(db: RootDatabase) -> AnalysisHost {
175        AnalysisHost { db }
176    }
177
178    pub fn update_lru_capacity(&mut self, lru_capacity: Option<u16>) {
179        self.db.update_base_query_lru_capacities(lru_capacity);
180    }
181
182    pub fn update_lru_capacities(&mut self, lru_capacities: &FxHashMap<Box<str>, u16>) {
183        self.db.update_lru_capacities(lru_capacities);
184    }
185
186    /// Returns a snapshot of the current state, which you can query for
187    /// semantic information.
188    pub fn analysis(&self) -> Analysis {
189        Analysis { db: self.db.clone() }
190    }
191
192    /// Applies changes to the current state of the world. If there are
193    /// outstanding snapshots, they will be canceled.
194    pub fn apply_change(&mut self, change: ChangeWithProcMacros) {
195        self.db.apply_change(change);
196    }
197
198    /// NB: this clears the database
199    pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes, usize)> {
200        self.db.per_query_memory_usage()
201    }
202    pub fn trigger_cancellation(&mut self) {
203        self.db.trigger_cancellation();
204    }
205    pub fn trigger_garbage_collection(&mut self) {
206        self.db.trigger_lru_eviction();
207        // SAFETY: `trigger_lru_eviction` triggers cancellation, so all running queries were canceled.
208        unsafe { hir::collect_ty_garbage() };
209    }
210    pub fn raw_database(&self) -> &RootDatabase {
211        &self.db
212    }
213    pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
214        &mut self.db
215    }
216}
217
218impl Default for AnalysisHost {
219    fn default() -> AnalysisHost {
220        AnalysisHost::new(None)
221    }
222}
223
224/// Analysis is a snapshot of a world state at a moment in time. It is the main
225/// entry point for asking semantic information about the world. When the world
226/// state is advanced using `AnalysisHost::apply_change` method, all existing
227/// `Analysis` are canceled (most method return `Err(Canceled)`).
228#[derive(Debug)]
229pub struct Analysis {
230    db: RootDatabase,
231}
232
233// As a general design guideline, `Analysis` API are intended to be independent
234// from the language server protocol. That is, when exposing some functionality
235// we should think in terms of "what API makes most sense" and not in terms of
236// "what types LSP uses". Although currently LSP is the only consumer of the
237// API, the API should in theory be usable as a library, or via a different
238// protocol.
239impl Analysis {
240    // Creates an analysis instance for a single file, without any external
241    // dependencies, stdlib support or ability to apply changes. See
242    // `AnalysisHost` for creating a fully-featured analysis.
243    pub fn from_single_file(text: String) -> (Analysis, FileId) {
244        let mut host = AnalysisHost::default();
245        let file_id = FileId::from_raw(0);
246        let mut file_set = FileSet::default();
247        file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_owned()));
248        let source_root = SourceRoot::new_local(file_set);
249
250        let mut change = ChangeWithProcMacros::default();
251        change.set_roots(vec![source_root]);
252        let mut crate_graph = CrateGraphBuilder::default();
253        // FIXME: cfg options
254        // Default to enable test for single file.
255        let mut cfg_options = CfgOptions::default();
256
257        // FIXME: This is less than ideal
258        let proc_macro_cwd = Arc::new(
259            TryFrom::try_from(&*std::env::current_dir().unwrap().as_path().to_string_lossy())
260                .unwrap(),
261        );
262        let crate_attrs = Vec::new();
263        cfg_options.insert_atom(sym::test);
264        crate_graph.add_crate_root(
265            file_id,
266            Edition::CURRENT,
267            None,
268            None,
269            cfg_options,
270            None,
271            Env::default(),
272            CrateOrigin::Local { repo: None, name: None },
273            crate_attrs,
274            false,
275            proc_macro_cwd,
276            Arc::new(CrateWorkspaceData {
277                target: Err("fixture has no layout".into()),
278                toolchain: None,
279            }),
280        );
281        change.change_file(file_id, Some(text));
282        change.set_crate_graph(crate_graph);
283
284        host.apply_change(change);
285        (host.analysis(), file_id)
286    }
287
288    pub(crate) fn from_ra_fixture(
289        sema: &Semantics<'_, RootDatabase>,
290        literal: ast::String,
291        expanded: &ast::String,
292        minicore: MiniCore<'_>,
293    ) -> Option<(Analysis, RaFixtureAnalysis)> {
294        Self::from_ra_fixture_with_on_cursor(sema, literal, expanded, minicore, &mut |_| {})
295    }
296
297    /// Like [`Analysis::from_ra_fixture()`], but also calls `on_cursor` with the cursor position.
298    pub(crate) fn from_ra_fixture_with_on_cursor(
299        sema: &Semantics<'_, RootDatabase>,
300        literal: ast::String,
301        expanded: &ast::String,
302        minicore: MiniCore<'_>,
303        on_cursor: &mut dyn FnMut(TextRange),
304    ) -> Option<(Analysis, RaFixtureAnalysis)> {
305        let analysis =
306            RaFixtureAnalysis::analyze_ra_fixture(sema, literal, expanded, minicore, on_cursor)?;
307        Some((Analysis { db: analysis.db.clone() }, analysis))
308    }
309
310    /// Debug info about the current state of the analysis.
311    pub fn status(&self, file_id: Option<FileId>) -> Cancellable<String> {
312        self.with_db(|db| status::status(db, file_id))
313    }
314
315    pub fn source_root_id(&self, file_id: FileId) -> Cancellable<SourceRootId> {
316        self.with_db(|db| db.file_source_root(file_id).source_root_id(db))
317    }
318
319    pub fn is_local_source_root(&self, source_root_id: SourceRootId) -> Cancellable<bool> {
320        self.with_db(|db| {
321            let sr = db.source_root(source_root_id).source_root(db);
322            !sr.is_library
323        })
324    }
325
326    pub fn parallel_prime_caches<F>(&self, num_worker_threads: usize, cb: F) -> Cancellable<()>
327    where
328        F: Fn(ParallelPrimeCachesProgress) + Sync + std::panic::UnwindSafe,
329    {
330        self.with_db(move |db| prime_caches::parallel_prime_caches(db, num_worker_threads, &cb))
331    }
332
333    /// Gets the text of the source file.
334    pub fn file_text(&self, file_id: FileId) -> Cancellable<Arc<str>> {
335        self.with_db(|db| SourceDatabase::file_text(db, file_id).text(db).clone())
336    }
337
338    /// Gets the syntax tree of the file.
339    pub fn parse(&self, file_id: FileId) -> Cancellable<SourceFile> {
340        // FIXME edition
341        self.with_db(|db| {
342            let editioned_file_id_wrapper =
343                EditionedFileId::current_edition_guess_origin(&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_guess_origin(&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_guess_origin(&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 =
475                EditionedFileId::current_edition_guess_origin(&self.db, file_id);
476            let source_file = db.parse(editioned_file_id_wrapper).tree();
477            file_structure::file_structure(&source_file, config)
478        })
479    }
480
481    /// Returns a list of the places in the file where type hints can be displayed.
482    pub fn inlay_hints(
483        &self,
484        config: &InlayHintsConfig<'_>,
485        file_id: FileId,
486        range: Option<TextRange>,
487    ) -> Cancellable<Vec<InlayHint>> {
488        self.with_db(|db| inlay_hints::inlay_hints(db, file_id, range, config))
489    }
490    pub fn inlay_hints_resolve(
491        &self,
492        config: &InlayHintsConfig<'_>,
493        file_id: FileId,
494        resolve_range: TextRange,
495        hash: u64,
496        hasher: impl Fn(&InlayHint) -> u64 + Send + UnwindSafe,
497    ) -> Cancellable<Option<InlayHint>> {
498        self.with_db(|db| {
499            inlay_hints::inlay_hints_resolve(db, file_id, resolve_range, hash, config, hasher)
500        })
501    }
502
503    /// Returns the set of folding ranges.
504    pub fn folding_ranges(&self, file_id: FileId) -> Cancellable<Vec<Fold>> {
505        self.with_db(|db| {
506            let editioned_file_id_wrapper =
507                EditionedFileId::current_edition_guess_origin(&self.db, file_id);
508
509            folding_ranges::folding_ranges(&db.parse(editioned_file_id_wrapper).tree())
510        })
511    }
512
513    /// Fuzzy searches for a symbol.
514    pub fn symbol_search(&self, query: Query, limit: usize) -> Cancellable<Vec<NavigationTarget>> {
515        // `world_symbols` currently clones the database to run stuff in parallel, which will make any query panic
516        // if we were to attach it here.
517        Cancelled::catch(|| {
518            let symbols = symbol_index::world_symbols(&self.db, query);
519            hir::attach_db(&self.db, || {
520                symbols
521                    .into_iter()
522                    .filter_map(|s| s.try_to_nav(&Semantics::new(&self.db)))
523                    .take(limit)
524                    .map(UpmappingResult::call_site)
525                    .collect::<Vec<_>>()
526            })
527        })
528    }
529
530    /// Returns the definitions from the symbol at `position`.
531    pub fn goto_definition(
532        &self,
533        position: FilePosition,
534        config: &GotoDefinitionConfig<'_>,
535    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
536        self.with_db(|db| goto_definition::goto_definition(db, position, config))
537    }
538
539    /// Returns the declaration from the symbol at `position`.
540    pub fn goto_declaration(
541        &self,
542        position: FilePosition,
543        config: &GotoDefinitionConfig<'_>,
544    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
545        self.with_db(|db| goto_declaration::goto_declaration(db, position, config))
546    }
547
548    /// Returns the impls from the symbol at `position`.
549    pub fn goto_implementation(
550        &self,
551        config: &GotoImplementationConfig,
552        position: FilePosition,
553    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
554        self.with_db(|db| goto_implementation::goto_implementation(db, config, position))
555    }
556
557    /// Returns the type definitions for the symbol at `position`.
558    pub fn goto_type_definition(
559        &self,
560        position: FilePosition,
561    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
562        self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
563    }
564
565    pub fn find_all_refs(
566        &self,
567        position: FilePosition,
568        config: &FindAllRefsConfig<'_>,
569    ) -> Cancellable<Option<Vec<ReferenceSearchResult>>> {
570        let config = AssertUnwindSafe(config);
571        self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, &config))
572    }
573
574    /// Returns a short text describing element at position.
575    pub fn hover(
576        &self,
577        config: &HoverConfig<'_>,
578        range: FileRange,
579    ) -> Cancellable<Option<RangeInfo<HoverResult>>> {
580        self.with_db(|db| hover::hover(db, range, config))
581    }
582
583    /// Returns moniker of symbol at position.
584    pub fn moniker(
585        &self,
586        position: FilePosition,
587    ) -> Cancellable<Option<RangeInfo<Vec<moniker::MonikerResult>>>> {
588        self.with_db(|db| moniker::moniker(db, position))
589    }
590
591    /// Returns URL(s) for the documentation of the symbol under the cursor.
592    /// # Arguments
593    /// * `position` - Position in the file.
594    /// * `target_dir` - Directory where the build output is stored.
595    pub fn external_docs(
596        &self,
597        position: FilePosition,
598        target_dir: Option<&str>,
599        sysroot: Option<&str>,
600    ) -> Cancellable<doc_links::DocumentationLinks> {
601        self.with_db(|db| {
602            doc_links::external_docs(db, position, target_dir, sysroot).unwrap_or_default()
603        })
604    }
605
606    /// Computes parameter information at the given position.
607    pub fn signature_help(&self, position: FilePosition) -> Cancellable<Option<SignatureHelp>> {
608        self.with_db(|db| signature_help::signature_help(db, position))
609    }
610
611    /// Computes call hierarchy candidates for the given file position.
612    pub fn call_hierarchy(
613        &self,
614        position: FilePosition,
615        config: &CallHierarchyConfig<'_>,
616    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
617        self.with_db(|db| call_hierarchy::call_hierarchy(db, position, config))
618    }
619
620    /// Computes incoming calls for the given file position.
621    pub fn incoming_calls(
622        &self,
623        config: &CallHierarchyConfig<'_>,
624        position: FilePosition,
625    ) -> Cancellable<Option<Vec<CallItem>>> {
626        self.with_db(|db| call_hierarchy::incoming_calls(db, config, position))
627    }
628
629    /// Computes outgoing calls for the given file position.
630    pub fn outgoing_calls(
631        &self,
632        config: &CallHierarchyConfig<'_>,
633        position: FilePosition,
634    ) -> Cancellable<Option<Vec<CallItem>>> {
635        self.with_db(|db| call_hierarchy::outgoing_calls(db, config, position))
636    }
637
638    /// Returns a `mod name;` declaration which created the current module.
639    pub fn parent_module(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
640        self.with_db(|db| parent_module::parent_module(db, position))
641    }
642
643    /// Returns vec of `mod name;` declaration which are created by the current module.
644    pub fn child_modules(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
645        self.with_db(|db| child_modules::child_modules(db, position))
646    }
647
648    /// Returns crates that this file belongs to.
649    pub fn crates_for(&self, file_id: FileId) -> Cancellable<Vec<Crate>> {
650        self.with_db(|db| parent_module::crates_for(db, file_id))
651    }
652
653    /// Returns crates that this file belongs to.
654    pub fn transitive_rev_deps(&self, crate_id: Crate) -> Cancellable<Vec<Crate>> {
655        self.with_db(|db| Vec::from_iter(crate_id.transitive_rev_deps(db)))
656    }
657
658    /// Returns crates that this file *might* belong to.
659    pub fn relevant_crates_for(&self, file_id: FileId) -> Cancellable<Vec<Crate>> {
660        self.with_db(|db| db.relevant_crates(file_id).iter().copied().collect())
661    }
662
663    /// Returns the edition of the given crate.
664    pub fn crate_edition(&self, crate_id: Crate) -> Cancellable<Edition> {
665        self.with_db(|db| crate_id.data(db).edition)
666    }
667
668    /// Returns whether the given crate is a proc macro.
669    pub fn is_proc_macro_crate(&self, crate_id: Crate) -> Cancellable<bool> {
670        self.with_db(|db| crate_id.data(db).is_proc_macro)
671    }
672
673    /// Returns true if this crate has `no_std` or `no_core` specified.
674    pub fn is_crate_no_std(&self, crate_id: Crate) -> Cancellable<bool> {
675        self.with_db(|db| crate_def_map(db, crate_id).is_no_std())
676    }
677
678    /// Returns the root file of the given crate.
679    pub fn crate_root(&self, crate_id: Crate) -> Cancellable<FileId> {
680        self.with_db(|db| crate_id.data(db).root_file_id)
681    }
682
683    /// Returns the set of possible targets to run for the current file.
684    pub fn runnables(&self, file_id: FileId) -> Cancellable<Vec<Runnable>> {
685        self.with_db(|db| runnables::runnables(db, file_id))
686    }
687
688    /// Returns the set of tests for the given file position.
689    pub fn related_tests(
690        &self,
691        position: FilePosition,
692        search_scope: Option<SearchScope>,
693    ) -> Cancellable<Vec<Runnable>> {
694        let search_scope = AssertUnwindSafe(search_scope);
695        self.with_db(|db| {
696            let _ = &search_scope;
697            runnables::related_tests(db, position, search_scope.0)
698        })
699    }
700
701    /// Computes all ranges to highlight for a given item in a file.
702    pub fn highlight_related(
703        &self,
704        config: HighlightRelatedConfig,
705        position: FilePosition,
706    ) -> Cancellable<Option<Vec<HighlightedRange>>> {
707        self.with_db(|db| {
708            highlight_related::highlight_related(&Semantics::new(db), config, position)
709        })
710    }
711
712    /// Computes syntax highlighting for the given file
713    pub fn highlight(
714        &self,
715        highlight_config: HighlightConfig<'_>,
716        file_id: FileId,
717    ) -> Cancellable<Vec<HlRange>> {
718        self.with_db(|db| syntax_highlighting::highlight(db, &highlight_config, file_id, None))
719    }
720
721    /// Computes syntax highlighting for the given file range.
722    pub fn highlight_range(
723        &self,
724        highlight_config: HighlightConfig<'_>,
725        frange: FileRange,
726    ) -> Cancellable<Vec<HlRange>> {
727        self.with_db(|db| {
728            syntax_highlighting::highlight(
729                db,
730                &highlight_config,
731                frange.file_id,
732                Some(frange.range),
733            )
734        })
735    }
736
737    /// Computes syntax highlighting for the given file.
738    pub fn highlight_as_html_with_config(
739        &self,
740        config: HighlightConfig<'_>,
741        file_id: FileId,
742        rainbow: bool,
743    ) -> Cancellable<String> {
744        self.with_db(|db| {
745            syntax_highlighting::highlight_as_html_with_config(db, &config, file_id, rainbow)
746        })
747    }
748
749    /// Computes syntax highlighting for the given file.
750    pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancellable<String> {
751        self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
752    }
753
754    /// Computes completions at the given position.
755    pub fn completions(
756        &self,
757        config: &CompletionConfig<'_>,
758        position: FilePosition,
759        trigger_character: Option<char>,
760    ) -> Cancellable<Option<Vec<CompletionItem>>> {
761        self.with_db(|db| ide_completion::completions(db, config, position, trigger_character))
762    }
763
764    /// Resolves additional completion data at the position given.
765    pub fn resolve_completion_edits(
766        &self,
767        config: &CompletionConfig<'_>,
768        position: FilePosition,
769        imports: impl IntoIterator<Item = String> + std::panic::UnwindSafe,
770    ) -> Cancellable<Vec<TextEdit>> {
771        Ok(self
772            .with_db(|db| ide_completion::resolve_completion_edits(db, config, position, imports))?
773            .unwrap_or_default())
774    }
775
776    /// Computes the set of parser level diagnostics for the given file.
777    pub fn syntax_diagnostics(
778        &self,
779        config: &DiagnosticsConfig,
780        file_id: FileId,
781    ) -> Cancellable<Vec<Diagnostic>> {
782        self.with_db(|db| ide_diagnostics::syntax_diagnostics(db, config, file_id))
783    }
784
785    /// Computes the set of semantic diagnostics for the given file.
786    pub fn semantic_diagnostics(
787        &self,
788        config: &DiagnosticsConfig,
789        resolve: AssistResolveStrategy,
790        file_id: FileId,
791    ) -> Cancellable<Vec<Diagnostic>> {
792        self.with_db(|db| ide_diagnostics::semantic_diagnostics(db, config, &resolve, file_id))
793    }
794
795    /// Computes the set of both syntax and semantic diagnostics for the given file.
796    pub fn full_diagnostics(
797        &self,
798        config: &DiagnosticsConfig,
799        resolve: AssistResolveStrategy,
800        file_id: FileId,
801    ) -> Cancellable<Vec<Diagnostic>> {
802        self.with_db(|db| ide_diagnostics::full_diagnostics(db, config, &resolve, file_id))
803    }
804
805    /// Convenience function to return assists + quick fixes for diagnostics
806    pub fn assists_with_fixes(
807        &self,
808        assist_config: &AssistConfig,
809        diagnostics_config: &DiagnosticsConfig,
810        resolve: AssistResolveStrategy,
811        frange: FileRange,
812    ) -> Cancellable<Vec<Assist>> {
813        let include_fixes = match &assist_config.allowed {
814            Some(it) => it.contains(&AssistKind::QuickFix),
815            None => true,
816        };
817
818        self.with_db(|db| {
819            let diagnostic_assists = if diagnostics_config.enabled && include_fixes {
820                ide_diagnostics::full_diagnostics(db, diagnostics_config, &resolve, frange.file_id)
821                    .into_iter()
822                    .flat_map(|it| it.fixes.unwrap_or_default())
823                    .filter(|it| it.target.intersect(frange.range).is_some())
824                    .collect()
825            } else {
826                Vec::new()
827            };
828            let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
829            let assists = ide_assists::assists(db, assist_config, resolve, frange);
830
831            let mut res = diagnostic_assists;
832            res.extend(ssr_assists);
833            res.extend(assists);
834
835            res
836        })
837    }
838
839    /// Returns the edit required to rename reference at the position to the new
840    /// name.
841    pub fn rename(
842        &self,
843        position: FilePosition,
844        new_name: &str,
845        config: &RenameConfig,
846    ) -> Cancellable<Result<SourceChange, RenameError>> {
847        self.with_db(|db| rename::rename(db, position, new_name, config))
848    }
849
850    pub fn prepare_rename(
851        &self,
852        position: FilePosition,
853    ) -> Cancellable<Result<RangeInfo<()>, RenameError>> {
854        self.with_db(|db| rename::prepare_rename(db, position))
855    }
856
857    pub fn will_rename_file(
858        &self,
859        file_id: FileId,
860        new_name_stem: &str,
861        config: &RenameConfig,
862    ) -> Cancellable<Option<SourceChange>> {
863        self.with_db(|db| rename::will_rename_file(db, file_id, new_name_stem, config))
864    }
865
866    pub fn structural_search_replace(
867        &self,
868        query: &str,
869        parse_only: bool,
870        resolve_context: FilePosition,
871        selections: Vec<FileRange>,
872    ) -> Cancellable<Result<SourceChange, SsrError>> {
873        self.with_db(|db| {
874            let rule: ide_ssr::SsrRule = query.parse()?;
875            let mut match_finder =
876                ide_ssr::MatchFinder::in_context(db, resolve_context, selections)?;
877            match_finder.add_rule(rule)?;
878            let edits = if parse_only { Default::default() } else { match_finder.edits() };
879            Ok(SourceChange::from_iter(edits))
880        })
881    }
882
883    pub fn annotations(
884        &self,
885        config: &AnnotationConfig<'_>,
886        file_id: FileId,
887    ) -> Cancellable<Vec<Annotation>> {
888        self.with_db(|db| annotations::annotations(db, config, file_id))
889    }
890
891    pub fn resolve_annotation(
892        &self,
893        config: &AnnotationConfig<'_>,
894        annotation: Annotation,
895    ) -> Cancellable<Annotation> {
896        self.with_db(|db| annotations::resolve_annotation(db, config, annotation))
897    }
898
899    pub fn move_item(
900        &self,
901        range: FileRange,
902        direction: Direction,
903    ) -> Cancellable<Option<TextEdit>> {
904        self.with_db(|db| move_item::move_item(db, range, direction))
905    }
906
907    pub fn get_recursive_memory_layout(
908        &self,
909        position: FilePosition,
910    ) -> Cancellable<Option<RecursiveMemoryLayout>> {
911        self.with_db(|db| view_memory_layout(db, position))
912    }
913
914    pub fn get_failed_obligations(&self, offset: TextSize, file_id: FileId) -> Cancellable<String> {
915        self.with_db(|db| {
916            let sema = Semantics::new(db);
917            let source_file = sema.parse_guess_edition(file_id);
918
919            let Some(token) = source_file.syntax().token_at_offset(offset).next() else {
920                return String::new();
921            };
922            sema.get_failed_obligations(token).unwrap_or_default()
923        })
924    }
925
926    pub fn editioned_file_id_to_vfs(&self, file_id: hir::EditionedFileId) -> FileId {
927        file_id.file_id(&self.db)
928    }
929
930    /// Performs an operation on the database that may be canceled.
931    ///
932    /// rust-analyzer needs to be able to answer semantic questions about the
933    /// code while the code is being modified. A common problem is that a
934    /// long-running query is being calculated when a new change arrives.
935    ///
936    /// We can't just apply the change immediately: this will cause the pending
937    /// query to see inconsistent state (it will observe an absence of
938    /// repeatable read). So what we do is we **cancel** all pending queries
939    /// before applying the change.
940    ///
941    /// Salsa implements cancellation by unwinding with a special value and
942    /// catching it on the API boundary.
943    fn with_db<F, T>(&self, f: F) -> Cancellable<T>
944    where
945        F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
946    {
947        // We use `attach_db_allow_change()` and not `attach_db()` because fixture injection can change the database.
948        hir::attach_db_allow_change(&self.db, || Cancelled::catch(|| f(&self.db)))
949    }
950}
951
952#[test]
953fn analysis_is_send() {
954    fn is_send<T: Send>() {}
955    is_send::<Analysis>();
956}