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,
71    },
72    prime_caches, symbol_index,
73};
74use ide_db::{MiniCore, ra_fixture::RaFixtureAnalysis};
75use macros::UpmapFromRaFixture;
76use syntax::{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 request_cancellation(&mut self) {
203        self.db.request_cancellation();
204    }
205    pub fn raw_database(&self) -> &RootDatabase {
206        &self.db
207    }
208    pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
209        &mut self.db
210    }
211}
212
213impl Default for AnalysisHost {
214    fn default() -> AnalysisHost {
215        AnalysisHost::new(None)
216    }
217}
218
219/// Analysis is a snapshot of a world state at a moment in time. It is the main
220/// entry point for asking semantic information about the world. When the world
221/// state is advanced using `AnalysisHost::apply_change` method, all existing
222/// `Analysis` are canceled (most method return `Err(Canceled)`).
223#[derive(Debug)]
224pub struct Analysis {
225    db: RootDatabase,
226}
227
228// As a general design guideline, `Analysis` API are intended to be independent
229// from the language server protocol. That is, when exposing some functionality
230// we should think in terms of "what API makes most sense" and not in terms of
231// "what types LSP uses". Although currently LSP is the only consumer of the
232// API, the API should in theory be usable as a library, or via a different
233// protocol.
234impl Analysis {
235    // Creates an analysis instance for a single file, without any external
236    // dependencies, stdlib support or ability to apply changes. See
237    // `AnalysisHost` for creating a fully-featured analysis.
238    pub fn from_single_file(text: String) -> (Analysis, FileId) {
239        let mut host = AnalysisHost::default();
240        let file_id = FileId::from_raw(0);
241        let mut file_set = FileSet::default();
242        file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_owned()));
243        let source_root = SourceRoot::new_local(file_set);
244
245        let mut change = ChangeWithProcMacros::default();
246        change.set_roots(vec![source_root]);
247        let mut crate_graph = CrateGraphBuilder::default();
248        // FIXME: cfg options
249        // Default to enable test for single file.
250        let mut cfg_options = CfgOptions::default();
251
252        // FIXME: This is less than ideal
253        let proc_macro_cwd = Arc::new(
254            TryFrom::try_from(&*std::env::current_dir().unwrap().as_path().to_string_lossy())
255                .unwrap(),
256        );
257        cfg_options.insert_atom(sym::test);
258        crate_graph.add_crate_root(
259            file_id,
260            Edition::CURRENT,
261            None,
262            None,
263            cfg_options,
264            None,
265            Env::default(),
266            CrateOrigin::Local { repo: None, name: None },
267            false,
268            proc_macro_cwd,
269            Arc::new(CrateWorkspaceData {
270                target: Err("fixture has no layout".into()),
271                toolchain: None,
272            }),
273        );
274        change.change_file(file_id, Some(text));
275        change.set_crate_graph(crate_graph);
276
277        host.apply_change(change);
278        (host.analysis(), file_id)
279    }
280
281    pub(crate) fn from_ra_fixture(
282        sema: &Semantics<'_, RootDatabase>,
283        literal: ast::String,
284        expanded: &ast::String,
285        minicore: MiniCore<'_>,
286    ) -> Option<(Analysis, RaFixtureAnalysis)> {
287        Self::from_ra_fixture_with_on_cursor(sema, literal, expanded, minicore, &mut |_| {})
288    }
289
290    /// Like [`Analysis::from_ra_fixture()`], but also calls `on_cursor` with the cursor position.
291    pub(crate) fn from_ra_fixture_with_on_cursor(
292        sema: &Semantics<'_, RootDatabase>,
293        literal: ast::String,
294        expanded: &ast::String,
295        minicore: MiniCore<'_>,
296        on_cursor: &mut dyn FnMut(TextRange),
297    ) -> Option<(Analysis, RaFixtureAnalysis)> {
298        let analysis =
299            RaFixtureAnalysis::analyze_ra_fixture(sema, literal, expanded, minicore, on_cursor)?;
300        Some((Analysis { db: analysis.db.clone() }, analysis))
301    }
302
303    /// Debug info about the current state of the analysis.
304    pub fn status(&self, file_id: Option<FileId>) -> Cancellable<String> {
305        self.with_db(|db| status::status(db, file_id))
306    }
307
308    pub fn source_root_id(&self, file_id: FileId) -> Cancellable<SourceRootId> {
309        self.with_db(|db| db.file_source_root(file_id).source_root_id(db))
310    }
311
312    pub fn is_local_source_root(&self, source_root_id: SourceRootId) -> Cancellable<bool> {
313        self.with_db(|db| {
314            let sr = db.source_root(source_root_id).source_root(db);
315            !sr.is_library
316        })
317    }
318
319    pub fn parallel_prime_caches<F>(&self, num_worker_threads: usize, cb: F) -> Cancellable<()>
320    where
321        F: Fn(ParallelPrimeCachesProgress) + Sync + std::panic::UnwindSafe,
322    {
323        self.with_db(move |db| prime_caches::parallel_prime_caches(db, num_worker_threads, &cb))
324    }
325
326    /// Gets the text of the source file.
327    pub fn file_text(&self, file_id: FileId) -> Cancellable<Arc<str>> {
328        self.with_db(|db| SourceDatabase::file_text(db, file_id).text(db).clone())
329    }
330
331    /// Gets the syntax tree of the file.
332    pub fn parse(&self, file_id: FileId) -> Cancellable<SourceFile> {
333        // FIXME edition
334        self.with_db(|db| {
335            let editioned_file_id_wrapper =
336                EditionedFileId::current_edition_guess_origin(&self.db, file_id);
337
338            db.parse(editioned_file_id_wrapper).tree()
339        })
340    }
341
342    /// Returns true if this file belongs to an immutable library.
343    pub fn is_library_file(&self, file_id: FileId) -> Cancellable<bool> {
344        self.with_db(|db| {
345            let source_root = db.file_source_root(file_id).source_root_id(db);
346            db.source_root(source_root).source_root(db).is_library
347        })
348    }
349
350    /// Gets the file's `LineIndex`: data structure to convert between absolute
351    /// offsets and line/column representation.
352    pub fn file_line_index(&self, file_id: FileId) -> Cancellable<Arc<LineIndex>> {
353        self.with_db(|db| db.line_index(file_id))
354    }
355
356    /// Selects the next syntactic nodes encompassing the range.
357    pub fn extend_selection(&self, frange: FileRange) -> Cancellable<TextRange> {
358        self.with_db(|db| extend_selection::extend_selection(db, frange))
359    }
360
361    /// Returns position of the matching brace (all types of braces are
362    /// supported).
363    pub fn matching_brace(&self, position: FilePosition) -> Cancellable<Option<TextSize>> {
364        self.with_db(|db| {
365            let file_id = EditionedFileId::current_edition_guess_origin(&self.db, position.file_id);
366            let parse = db.parse(file_id);
367            let file = parse.tree();
368            matching_brace::matching_brace(&file, position.offset)
369        })
370    }
371
372    pub fn view_syntax_tree(&self, file_id: FileId) -> Cancellable<String> {
373        self.with_db(|db| view_syntax_tree::view_syntax_tree(db, file_id))
374    }
375
376    pub fn view_hir(&self, position: FilePosition) -> Cancellable<String> {
377        self.with_db(|db| view_hir::view_hir(db, position))
378    }
379
380    pub fn view_mir(&self, position: FilePosition) -> Cancellable<String> {
381        self.with_db(|db| view_mir::view_mir(db, position))
382    }
383
384    pub fn interpret_function(&self, position: FilePosition) -> Cancellable<String> {
385        self.with_db(|db| interpret::interpret(db, position))
386    }
387
388    pub fn view_item_tree(&self, file_id: FileId) -> Cancellable<String> {
389        self.with_db(|db| view_item_tree::view_item_tree(db, file_id))
390    }
391
392    pub fn discover_test_roots(&self) -> Cancellable<Vec<TestItem>> {
393        self.with_db(test_explorer::discover_test_roots)
394    }
395
396    pub fn discover_tests_in_crate_by_test_id(&self, crate_id: &str) -> Cancellable<Vec<TestItem>> {
397        self.with_db(|db| test_explorer::discover_tests_in_crate_by_test_id(db, crate_id))
398    }
399
400    pub fn discover_tests_in_crate(&self, crate_id: Crate) -> Cancellable<Vec<TestItem>> {
401        self.with_db(|db| test_explorer::discover_tests_in_crate(db, crate_id))
402    }
403
404    pub fn discover_tests_in_file(&self, file_id: FileId) -> Cancellable<Vec<TestItem>> {
405        self.with_db(|db| test_explorer::discover_tests_in_file(db, file_id))
406    }
407
408    /// Renders the crate graph to GraphViz "dot" syntax.
409    pub fn view_crate_graph(&self, full: bool) -> Cancellable<Result<String, String>> {
410        self.with_db(|db| view_crate_graph::view_crate_graph(db, full))
411    }
412
413    pub fn fetch_crates(&self) -> Cancellable<FxIndexSet<CrateInfo>> {
414        self.with_db(fetch_crates::fetch_crates)
415    }
416
417    pub fn expand_macro(&self, position: FilePosition) -> Cancellable<Option<ExpandedMacro>> {
418        self.with_db(|db| expand_macro::expand_macro(db, position))
419    }
420
421    /// Returns an edit to remove all newlines in the range, cleaning up minor
422    /// stuff like trailing commas.
423    pub fn join_lines(&self, config: &JoinLinesConfig, frange: FileRange) -> Cancellable<TextEdit> {
424        self.with_db(|db| {
425            let editioned_file_id_wrapper =
426                EditionedFileId::current_edition_guess_origin(&self.db, frange.file_id);
427            let parse = db.parse(editioned_file_id_wrapper);
428            join_lines::join_lines(config, &parse.tree(), frange.range)
429        })
430    }
431
432    /// Returns an edit which should be applied when opening a new line, fixing
433    /// up minor stuff like continuing the comment.
434    /// The edit will be a snippet (with `$0`).
435    pub fn on_enter(&self, position: FilePosition) -> Cancellable<Option<TextEdit>> {
436        self.with_db(|db| typing::on_enter(db, position))
437    }
438
439    pub const SUPPORTED_TRIGGER_CHARS: &[char] = typing::TRIGGER_CHARS;
440
441    /// Returns an edit which should be applied after a character was typed.
442    ///
443    /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
444    /// automatically.
445    pub fn on_char_typed(
446        &self,
447        position: FilePosition,
448        char_typed: char,
449    ) -> Cancellable<Option<SourceChange>> {
450        // Fast path to not even parse the file.
451        if !typing::TRIGGER_CHARS.contains(&char_typed) {
452            return Ok(None);
453        }
454
455        self.with_db(|db| typing::on_char_typed(db, position, char_typed))
456    }
457
458    /// Returns a tree representation of symbols in the file. Useful to draw a
459    /// file outline.
460    pub fn file_structure(
461        &self,
462        config: &FileStructureConfig,
463        file_id: FileId,
464    ) -> Cancellable<Vec<StructureNode>> {
465        // FIXME: Edition
466        self.with_db(|db| {
467            let editioned_file_id_wrapper =
468                EditionedFileId::current_edition_guess_origin(&self.db, file_id);
469            let source_file = db.parse(editioned_file_id_wrapper).tree();
470            file_structure::file_structure(&source_file, config)
471        })
472    }
473
474    /// Returns a list of the places in the file where type hints can be displayed.
475    pub fn inlay_hints(
476        &self,
477        config: &InlayHintsConfig<'_>,
478        file_id: FileId,
479        range: Option<TextRange>,
480    ) -> Cancellable<Vec<InlayHint>> {
481        self.with_db(|db| inlay_hints::inlay_hints(db, file_id, range, config))
482    }
483    pub fn inlay_hints_resolve(
484        &self,
485        config: &InlayHintsConfig<'_>,
486        file_id: FileId,
487        resolve_range: TextRange,
488        hash: u64,
489        hasher: impl Fn(&InlayHint) -> u64 + Send + UnwindSafe,
490    ) -> Cancellable<Option<InlayHint>> {
491        self.with_db(|db| {
492            inlay_hints::inlay_hints_resolve(db, file_id, resolve_range, hash, config, hasher)
493        })
494    }
495
496    /// Returns the set of folding ranges.
497    pub fn folding_ranges(&self, file_id: FileId) -> Cancellable<Vec<Fold>> {
498        self.with_db(|db| {
499            let editioned_file_id_wrapper =
500                EditionedFileId::current_edition_guess_origin(&self.db, file_id);
501
502            folding_ranges::folding_ranges(&db.parse(editioned_file_id_wrapper).tree())
503        })
504    }
505
506    /// Fuzzy searches for a symbol.
507    pub fn symbol_search(&self, query: Query, limit: usize) -> Cancellable<Vec<NavigationTarget>> {
508        // `world_symbols` currently clones the database to run stuff in parallel, which will make any query panic
509        // if we were to attach it here.
510        Cancelled::catch(|| {
511            let symbols = symbol_index::world_symbols(&self.db, query);
512            hir::attach_db(&self.db, || {
513                symbols
514                    .into_iter()
515                    .filter_map(|s| s.try_to_nav(&Semantics::new(&self.db)))
516                    .take(limit)
517                    .map(UpmappingResult::call_site)
518                    .collect::<Vec<_>>()
519            })
520        })
521    }
522
523    /// Returns the definitions from the symbol at `position`.
524    pub fn goto_definition(
525        &self,
526        position: FilePosition,
527        config: &GotoDefinitionConfig<'_>,
528    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
529        self.with_db(|db| goto_definition::goto_definition(db, position, config))
530    }
531
532    /// Returns the declaration from the symbol at `position`.
533    pub fn goto_declaration(
534        &self,
535        position: FilePosition,
536        config: &GotoDefinitionConfig<'_>,
537    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
538        self.with_db(|db| goto_declaration::goto_declaration(db, position, config))
539    }
540
541    /// Returns the impls from the symbol at `position`.
542    pub fn goto_implementation(
543        &self,
544        config: &GotoImplementationConfig,
545        position: FilePosition,
546    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
547        self.with_db(|db| goto_implementation::goto_implementation(db, config, position))
548    }
549
550    /// Returns the type definitions for the symbol at `position`.
551    pub fn goto_type_definition(
552        &self,
553        position: FilePosition,
554    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
555        self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
556    }
557
558    pub fn find_all_refs(
559        &self,
560        position: FilePosition,
561        config: &FindAllRefsConfig<'_>,
562    ) -> Cancellable<Option<Vec<ReferenceSearchResult>>> {
563        let config = AssertUnwindSafe(config);
564        self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, &config))
565    }
566
567    /// Returns a short text describing element at position.
568    pub fn hover(
569        &self,
570        config: &HoverConfig<'_>,
571        range: FileRange,
572    ) -> Cancellable<Option<RangeInfo<HoverResult>>> {
573        self.with_db(|db| hover::hover(db, range, config))
574    }
575
576    /// Returns moniker of symbol at position.
577    pub fn moniker(
578        &self,
579        position: FilePosition,
580    ) -> Cancellable<Option<RangeInfo<Vec<moniker::MonikerResult>>>> {
581        self.with_db(|db| moniker::moniker(db, position))
582    }
583
584    /// Returns URL(s) for the documentation of the symbol under the cursor.
585    /// # Arguments
586    /// * `position` - Position in the file.
587    /// * `target_dir` - Directory where the build output is stored.
588    pub fn external_docs(
589        &self,
590        position: FilePosition,
591        target_dir: Option<&str>,
592        sysroot: Option<&str>,
593    ) -> Cancellable<doc_links::DocumentationLinks> {
594        self.with_db(|db| {
595            doc_links::external_docs(db, position, target_dir, sysroot).unwrap_or_default()
596        })
597    }
598
599    /// Computes parameter information at the given position.
600    pub fn signature_help(&self, position: FilePosition) -> Cancellable<Option<SignatureHelp>> {
601        self.with_db(|db| signature_help::signature_help(db, position))
602    }
603
604    /// Computes call hierarchy candidates for the given file position.
605    pub fn call_hierarchy(
606        &self,
607        position: FilePosition,
608        config: &CallHierarchyConfig<'_>,
609    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
610        self.with_db(|db| call_hierarchy::call_hierarchy(db, position, config))
611    }
612
613    /// Computes incoming calls for the given file position.
614    pub fn incoming_calls(
615        &self,
616        config: &CallHierarchyConfig<'_>,
617        position: FilePosition,
618    ) -> Cancellable<Option<Vec<CallItem>>> {
619        self.with_db(|db| call_hierarchy::incoming_calls(db, config, position))
620    }
621
622    /// Computes outgoing calls for the given file position.
623    pub fn outgoing_calls(
624        &self,
625        config: &CallHierarchyConfig<'_>,
626        position: FilePosition,
627    ) -> Cancellable<Option<Vec<CallItem>>> {
628        self.with_db(|db| call_hierarchy::outgoing_calls(db, config, position))
629    }
630
631    /// Returns a `mod name;` declaration which created the current module.
632    pub fn parent_module(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
633        self.with_db(|db| parent_module::parent_module(db, position))
634    }
635
636    /// Returns vec of `mod name;` declaration which are created by the current module.
637    pub fn child_modules(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
638        self.with_db(|db| child_modules::child_modules(db, position))
639    }
640
641    /// Returns crates that this file belongs to.
642    pub fn crates_for(&self, file_id: FileId) -> Cancellable<Vec<Crate>> {
643        self.with_db(|db| parent_module::crates_for(db, file_id))
644    }
645
646    /// Returns crates that this file belongs to.
647    pub fn transitive_rev_deps(&self, crate_id: Crate) -> Cancellable<Vec<Crate>> {
648        self.with_db(|db| Vec::from_iter(crate_id.transitive_rev_deps(db)))
649    }
650
651    /// Returns crates that this file *might* belong to.
652    pub fn relevant_crates_for(&self, file_id: FileId) -> Cancellable<Vec<Crate>> {
653        self.with_db(|db| db.relevant_crates(file_id).iter().copied().collect())
654    }
655
656    /// Returns the edition of the given crate.
657    pub fn crate_edition(&self, crate_id: Crate) -> Cancellable<Edition> {
658        self.with_db(|db| crate_id.data(db).edition)
659    }
660
661    /// Returns whether the given crate is a proc macro.
662    pub fn is_proc_macro_crate(&self, crate_id: Crate) -> Cancellable<bool> {
663        self.with_db(|db| crate_id.data(db).is_proc_macro)
664    }
665
666    /// Returns true if this crate has `no_std` or `no_core` specified.
667    pub fn is_crate_no_std(&self, crate_id: Crate) -> Cancellable<bool> {
668        self.with_db(|db| crate_def_map(db, crate_id).is_no_std())
669    }
670
671    /// Returns the root file of the given crate.
672    pub fn crate_root(&self, crate_id: Crate) -> Cancellable<FileId> {
673        self.with_db(|db| crate_id.data(db).root_file_id)
674    }
675
676    /// Returns the set of possible targets to run for the current file.
677    pub fn runnables(&self, file_id: FileId) -> Cancellable<Vec<Runnable>> {
678        self.with_db(|db| runnables::runnables(db, file_id))
679    }
680
681    /// Returns the set of tests for the given file position.
682    pub fn related_tests(
683        &self,
684        position: FilePosition,
685        search_scope: Option<SearchScope>,
686    ) -> Cancellable<Vec<Runnable>> {
687        let search_scope = AssertUnwindSafe(search_scope);
688        self.with_db(|db| {
689            let _ = &search_scope;
690            runnables::related_tests(db, position, search_scope.0)
691        })
692    }
693
694    /// Computes all ranges to highlight for a given item in a file.
695    pub fn highlight_related(
696        &self,
697        config: HighlightRelatedConfig,
698        position: FilePosition,
699    ) -> Cancellable<Option<Vec<HighlightedRange>>> {
700        self.with_db(|db| {
701            highlight_related::highlight_related(&Semantics::new(db), config, position)
702        })
703    }
704
705    /// Computes syntax highlighting for the given file
706    pub fn highlight(
707        &self,
708        highlight_config: HighlightConfig<'_>,
709        file_id: FileId,
710    ) -> Cancellable<Vec<HlRange>> {
711        self.with_db(|db| syntax_highlighting::highlight(db, &highlight_config, file_id, None))
712    }
713
714    /// Computes syntax highlighting for the given file range.
715    pub fn highlight_range(
716        &self,
717        highlight_config: HighlightConfig<'_>,
718        frange: FileRange,
719    ) -> Cancellable<Vec<HlRange>> {
720        self.with_db(|db| {
721            syntax_highlighting::highlight(
722                db,
723                &highlight_config,
724                frange.file_id,
725                Some(frange.range),
726            )
727        })
728    }
729
730    /// Computes syntax highlighting for the given file.
731    pub fn highlight_as_html_with_config(
732        &self,
733        config: HighlightConfig<'_>,
734        file_id: FileId,
735        rainbow: bool,
736    ) -> Cancellable<String> {
737        self.with_db(|db| {
738            syntax_highlighting::highlight_as_html_with_config(db, &config, file_id, rainbow)
739        })
740    }
741
742    /// Computes syntax highlighting for the given file.
743    pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancellable<String> {
744        self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
745    }
746
747    /// Computes completions at the given position.
748    pub fn completions(
749        &self,
750        config: &CompletionConfig<'_>,
751        position: FilePosition,
752        trigger_character: Option<char>,
753    ) -> Cancellable<Option<Vec<CompletionItem>>> {
754        self.with_db(|db| ide_completion::completions(db, config, position, trigger_character))
755    }
756
757    /// Resolves additional completion data at the position given.
758    pub fn resolve_completion_edits(
759        &self,
760        config: &CompletionConfig<'_>,
761        position: FilePosition,
762        imports: impl IntoIterator<Item = String> + std::panic::UnwindSafe,
763    ) -> Cancellable<Vec<TextEdit>> {
764        Ok(self
765            .with_db(|db| ide_completion::resolve_completion_edits(db, config, position, imports))?
766            .unwrap_or_default())
767    }
768
769    /// Computes the set of parser level diagnostics for the given file.
770    pub fn syntax_diagnostics(
771        &self,
772        config: &DiagnosticsConfig,
773        file_id: FileId,
774    ) -> Cancellable<Vec<Diagnostic>> {
775        self.with_db(|db| ide_diagnostics::syntax_diagnostics(db, config, file_id))
776    }
777
778    /// Computes the set of semantic diagnostics for the given file.
779    pub fn semantic_diagnostics(
780        &self,
781        config: &DiagnosticsConfig,
782        resolve: AssistResolveStrategy,
783        file_id: FileId,
784    ) -> Cancellable<Vec<Diagnostic>> {
785        self.with_db(|db| ide_diagnostics::semantic_diagnostics(db, config, &resolve, file_id))
786    }
787
788    /// Computes the set of both syntax and semantic diagnostics for the given file.
789    pub fn full_diagnostics(
790        &self,
791        config: &DiagnosticsConfig,
792        resolve: AssistResolveStrategy,
793        file_id: FileId,
794    ) -> Cancellable<Vec<Diagnostic>> {
795        self.with_db(|db| ide_diagnostics::full_diagnostics(db, config, &resolve, file_id))
796    }
797
798    /// Convenience function to return assists + quick fixes for diagnostics
799    pub fn assists_with_fixes(
800        &self,
801        assist_config: &AssistConfig,
802        diagnostics_config: &DiagnosticsConfig,
803        resolve: AssistResolveStrategy,
804        frange: FileRange,
805    ) -> Cancellable<Vec<Assist>> {
806        let include_fixes = match &assist_config.allowed {
807            Some(it) => it.contains(&AssistKind::QuickFix),
808            None => true,
809        };
810
811        self.with_db(|db| {
812            let diagnostic_assists = if diagnostics_config.enabled && include_fixes {
813                ide_diagnostics::full_diagnostics(db, diagnostics_config, &resolve, frange.file_id)
814                    .into_iter()
815                    .flat_map(|it| it.fixes.unwrap_or_default())
816                    .filter(|it| it.target.intersect(frange.range).is_some())
817                    .collect()
818            } else {
819                Vec::new()
820            };
821            let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
822            let assists = ide_assists::assists(db, assist_config, resolve, frange);
823
824            let mut res = diagnostic_assists;
825            res.extend(ssr_assists);
826            res.extend(assists);
827
828            res
829        })
830    }
831
832    /// Returns the edit required to rename reference at the position to the new
833    /// name.
834    pub fn rename(
835        &self,
836        position: FilePosition,
837        new_name: &str,
838        config: &RenameConfig,
839    ) -> Cancellable<Result<SourceChange, RenameError>> {
840        self.with_db(|db| rename::rename(db, position, new_name, config))
841    }
842
843    pub fn prepare_rename(
844        &self,
845        position: FilePosition,
846    ) -> Cancellable<Result<RangeInfo<()>, RenameError>> {
847        self.with_db(|db| rename::prepare_rename(db, position))
848    }
849
850    pub fn will_rename_file(
851        &self,
852        file_id: FileId,
853        new_name_stem: &str,
854    ) -> Cancellable<Option<SourceChange>> {
855        self.with_db(|db| rename::will_rename_file(db, file_id, new_name_stem))
856    }
857
858    pub fn structural_search_replace(
859        &self,
860        query: &str,
861        parse_only: bool,
862        resolve_context: FilePosition,
863        selections: Vec<FileRange>,
864    ) -> Cancellable<Result<SourceChange, SsrError>> {
865        self.with_db(|db| {
866            let rule: ide_ssr::SsrRule = query.parse()?;
867            let mut match_finder =
868                ide_ssr::MatchFinder::in_context(db, resolve_context, selections)?;
869            match_finder.add_rule(rule)?;
870            let edits = if parse_only { Default::default() } else { match_finder.edits() };
871            Ok(SourceChange::from_iter(edits))
872        })
873    }
874
875    pub fn annotations(
876        &self,
877        config: &AnnotationConfig<'_>,
878        file_id: FileId,
879    ) -> Cancellable<Vec<Annotation>> {
880        self.with_db(|db| annotations::annotations(db, config, file_id))
881    }
882
883    pub fn resolve_annotation(
884        &self,
885        config: &AnnotationConfig<'_>,
886        annotation: Annotation,
887    ) -> Cancellable<Annotation> {
888        self.with_db(|db| annotations::resolve_annotation(db, config, annotation))
889    }
890
891    pub fn move_item(
892        &self,
893        range: FileRange,
894        direction: Direction,
895    ) -> Cancellable<Option<TextEdit>> {
896        self.with_db(|db| move_item::move_item(db, range, direction))
897    }
898
899    pub fn get_recursive_memory_layout(
900        &self,
901        position: FilePosition,
902    ) -> Cancellable<Option<RecursiveMemoryLayout>> {
903        self.with_db(|db| view_memory_layout(db, position))
904    }
905
906    pub fn editioned_file_id_to_vfs(&self, file_id: hir::EditionedFileId) -> FileId {
907        file_id.file_id(&self.db)
908    }
909
910    /// Performs an operation on the database that may be canceled.
911    ///
912    /// rust-analyzer needs to be able to answer semantic questions about the
913    /// code while the code is being modified. A common problem is that a
914    /// long-running query is being calculated when a new change arrives.
915    ///
916    /// We can't just apply the change immediately: this will cause the pending
917    /// query to see inconsistent state (it will observe an absence of
918    /// repeatable read). So what we do is we **cancel** all pending queries
919    /// before applying the change.
920    ///
921    /// Salsa implements cancellation by unwinding with a special value and
922    /// catching it on the API boundary.
923    fn with_db<F, T>(&self, f: F) -> Cancellable<T>
924    where
925        F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
926    {
927        // We use `attach_db_allow_change()` and not `attach_db()` because fixture injection can change the database.
928        hir::attach_db_allow_change(&self.db, || Cancelled::catch(|| f(&self.db)))
929    }
930}
931
932#[test]
933fn analysis_is_send() {
934    fn is_send<T: Send>() {}
935    is_send::<Analysis>();
936}