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 = EditionedFileId::current_edition(&self.db, file_id);
336
337            db.parse(editioned_file_id_wrapper).tree()
338        })
339    }
340
341    /// Returns true if this file belongs to an immutable library.
342    pub fn is_library_file(&self, file_id: FileId) -> Cancellable<bool> {
343        self.with_db(|db| {
344            let source_root = db.file_source_root(file_id).source_root_id(db);
345            db.source_root(source_root).source_root(db).is_library
346        })
347    }
348
349    /// Gets the file's `LineIndex`: data structure to convert between absolute
350    /// offsets and line/column representation.
351    pub fn file_line_index(&self, file_id: FileId) -> Cancellable<Arc<LineIndex>> {
352        self.with_db(|db| db.line_index(file_id))
353    }
354
355    /// Selects the next syntactic nodes encompassing the range.
356    pub fn extend_selection(&self, frange: FileRange) -> Cancellable<TextRange> {
357        self.with_db(|db| extend_selection::extend_selection(db, frange))
358    }
359
360    /// Returns position of the matching brace (all types of braces are
361    /// supported).
362    pub fn matching_brace(&self, position: FilePosition) -> Cancellable<Option<TextSize>> {
363        self.with_db(|db| {
364            let file_id = EditionedFileId::current_edition(&self.db, position.file_id);
365            let parse = db.parse(file_id);
366            let file = parse.tree();
367            matching_brace::matching_brace(&file, position.offset)
368        })
369    }
370
371    pub fn view_syntax_tree(&self, file_id: FileId) -> Cancellable<String> {
372        self.with_db(|db| view_syntax_tree::view_syntax_tree(db, file_id))
373    }
374
375    pub fn view_hir(&self, position: FilePosition) -> Cancellable<String> {
376        self.with_db(|db| view_hir::view_hir(db, position))
377    }
378
379    pub fn view_mir(&self, position: FilePosition) -> Cancellable<String> {
380        self.with_db(|db| view_mir::view_mir(db, position))
381    }
382
383    pub fn interpret_function(&self, position: FilePosition) -> Cancellable<String> {
384        self.with_db(|db| interpret::interpret(db, position))
385    }
386
387    pub fn view_item_tree(&self, file_id: FileId) -> Cancellable<String> {
388        self.with_db(|db| view_item_tree::view_item_tree(db, file_id))
389    }
390
391    pub fn discover_test_roots(&self) -> Cancellable<Vec<TestItem>> {
392        self.with_db(test_explorer::discover_test_roots)
393    }
394
395    pub fn discover_tests_in_crate_by_test_id(&self, crate_id: &str) -> Cancellable<Vec<TestItem>> {
396        self.with_db(|db| test_explorer::discover_tests_in_crate_by_test_id(db, crate_id))
397    }
398
399    pub fn discover_tests_in_crate(&self, crate_id: Crate) -> Cancellable<Vec<TestItem>> {
400        self.with_db(|db| test_explorer::discover_tests_in_crate(db, crate_id))
401    }
402
403    pub fn discover_tests_in_file(&self, file_id: FileId) -> Cancellable<Vec<TestItem>> {
404        self.with_db(|db| test_explorer::discover_tests_in_file(db, file_id))
405    }
406
407    /// Renders the crate graph to GraphViz "dot" syntax.
408    pub fn view_crate_graph(&self, full: bool) -> Cancellable<Result<String, String>> {
409        self.with_db(|db| view_crate_graph::view_crate_graph(db, full))
410    }
411
412    pub fn fetch_crates(&self) -> Cancellable<FxIndexSet<CrateInfo>> {
413        self.with_db(fetch_crates::fetch_crates)
414    }
415
416    pub fn expand_macro(&self, position: FilePosition) -> Cancellable<Option<ExpandedMacro>> {
417        self.with_db(|db| expand_macro::expand_macro(db, position))
418    }
419
420    /// Returns an edit to remove all newlines in the range, cleaning up minor
421    /// stuff like trailing commas.
422    pub fn join_lines(&self, config: &JoinLinesConfig, frange: FileRange) -> Cancellable<TextEdit> {
423        self.with_db(|db| {
424            let editioned_file_id_wrapper =
425                EditionedFileId::current_edition(&self.db, frange.file_id);
426            let parse = db.parse(editioned_file_id_wrapper);
427            join_lines::join_lines(config, &parse.tree(), frange.range)
428        })
429    }
430
431    /// Returns an edit which should be applied when opening a new line, fixing
432    /// up minor stuff like continuing the comment.
433    /// The edit will be a snippet (with `$0`).
434    pub fn on_enter(&self, position: FilePosition) -> Cancellable<Option<TextEdit>> {
435        self.with_db(|db| typing::on_enter(db, position))
436    }
437
438    pub const SUPPORTED_TRIGGER_CHARS: &[char] = typing::TRIGGER_CHARS;
439
440    /// Returns an edit which should be applied after a character was typed.
441    ///
442    /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
443    /// automatically.
444    pub fn on_char_typed(
445        &self,
446        position: FilePosition,
447        char_typed: char,
448    ) -> Cancellable<Option<SourceChange>> {
449        // Fast path to not even parse the file.
450        if !typing::TRIGGER_CHARS.contains(&char_typed) {
451            return Ok(None);
452        }
453
454        self.with_db(|db| typing::on_char_typed(db, position, char_typed))
455    }
456
457    /// Returns a tree representation of symbols in the file. Useful to draw a
458    /// file outline.
459    pub fn file_structure(
460        &self,
461        config: &FileStructureConfig,
462        file_id: FileId,
463    ) -> Cancellable<Vec<StructureNode>> {
464        // FIXME: Edition
465        self.with_db(|db| {
466            let editioned_file_id_wrapper = EditionedFileId::current_edition(&self.db, file_id);
467            let source_file = db.parse(editioned_file_id_wrapper).tree();
468            file_structure::file_structure(&source_file, config)
469        })
470    }
471
472    /// Returns a list of the places in the file where type hints can be displayed.
473    pub fn inlay_hints(
474        &self,
475        config: &InlayHintsConfig<'_>,
476        file_id: FileId,
477        range: Option<TextRange>,
478    ) -> Cancellable<Vec<InlayHint>> {
479        self.with_db(|db| inlay_hints::inlay_hints(db, file_id, range, config))
480    }
481    pub fn inlay_hints_resolve(
482        &self,
483        config: &InlayHintsConfig<'_>,
484        file_id: FileId,
485        resolve_range: TextRange,
486        hash: u64,
487        hasher: impl Fn(&InlayHint) -> u64 + Send + UnwindSafe,
488    ) -> Cancellable<Option<InlayHint>> {
489        self.with_db(|db| {
490            inlay_hints::inlay_hints_resolve(db, file_id, resolve_range, hash, config, hasher)
491        })
492    }
493
494    /// Returns the set of folding ranges.
495    pub fn folding_ranges(&self, file_id: FileId) -> Cancellable<Vec<Fold>> {
496        self.with_db(|db| {
497            let editioned_file_id_wrapper = EditionedFileId::current_edition(&self.db, file_id);
498
499            folding_ranges::folding_ranges(&db.parse(editioned_file_id_wrapper).tree())
500        })
501    }
502
503    /// Fuzzy searches for a symbol.
504    pub fn symbol_search(&self, query: Query, limit: usize) -> Cancellable<Vec<NavigationTarget>> {
505        // `world_symbols` currently clones the database to run stuff in parallel, which will make any query panic
506        // if we were to attach it here.
507        Cancelled::catch(|| {
508            let symbols = symbol_index::world_symbols(&self.db, query);
509            hir::attach_db(&self.db, || {
510                symbols
511                    .into_iter()
512                    .filter_map(|s| s.try_to_nav(&Semantics::new(&self.db)))
513                    .take(limit)
514                    .map(UpmappingResult::call_site)
515                    .collect::<Vec<_>>()
516            })
517        })
518    }
519
520    /// Returns the definitions from the symbol at `position`.
521    pub fn goto_definition(
522        &self,
523        position: FilePosition,
524        config: &GotoDefinitionConfig<'_>,
525    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
526        self.with_db(|db| goto_definition::goto_definition(db, position, config))
527    }
528
529    /// Returns the declaration from the symbol at `position`.
530    pub fn goto_declaration(
531        &self,
532        position: FilePosition,
533        config: &GotoDefinitionConfig<'_>,
534    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
535        self.with_db(|db| goto_declaration::goto_declaration(db, position, config))
536    }
537
538    /// Returns the impls from the symbol at `position`.
539    pub fn goto_implementation(
540        &self,
541        config: &GotoImplementationConfig,
542        position: FilePosition,
543    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
544        self.with_db(|db| goto_implementation::goto_implementation(db, config, position))
545    }
546
547    /// Returns the type definitions for the symbol at `position`.
548    pub fn goto_type_definition(
549        &self,
550        position: FilePosition,
551    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
552        self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
553    }
554
555    pub fn find_all_refs(
556        &self,
557        position: FilePosition,
558        config: &FindAllRefsConfig<'_>,
559    ) -> Cancellable<Option<Vec<ReferenceSearchResult>>> {
560        let config = AssertUnwindSafe(config);
561        self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, &config))
562    }
563
564    /// Returns a short text describing element at position.
565    pub fn hover(
566        &self,
567        config: &HoverConfig<'_>,
568        range: FileRange,
569    ) -> Cancellable<Option<RangeInfo<HoverResult>>> {
570        self.with_db(|db| hover::hover(db, range, config))
571    }
572
573    /// Returns moniker of symbol at position.
574    pub fn moniker(
575        &self,
576        position: FilePosition,
577    ) -> Cancellable<Option<RangeInfo<Vec<moniker::MonikerResult>>>> {
578        self.with_db(|db| moniker::moniker(db, position))
579    }
580
581    /// Returns URL(s) for the documentation of the symbol under the cursor.
582    /// # Arguments
583    /// * `position` - Position in the file.
584    /// * `target_dir` - Directory where the build output is stored.
585    pub fn external_docs(
586        &self,
587        position: FilePosition,
588        target_dir: Option<&str>,
589        sysroot: Option<&str>,
590    ) -> Cancellable<doc_links::DocumentationLinks> {
591        self.with_db(|db| {
592            doc_links::external_docs(db, position, target_dir, sysroot).unwrap_or_default()
593        })
594    }
595
596    /// Computes parameter information at the given position.
597    pub fn signature_help(&self, position: FilePosition) -> Cancellable<Option<SignatureHelp>> {
598        self.with_db(|db| signature_help::signature_help(db, position))
599    }
600
601    /// Computes call hierarchy candidates for the given file position.
602    pub fn call_hierarchy(
603        &self,
604        position: FilePosition,
605        config: &CallHierarchyConfig<'_>,
606    ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
607        self.with_db(|db| call_hierarchy::call_hierarchy(db, position, config))
608    }
609
610    /// Computes incoming calls for the given file position.
611    pub fn incoming_calls(
612        &self,
613        config: &CallHierarchyConfig<'_>,
614        position: FilePosition,
615    ) -> Cancellable<Option<Vec<CallItem>>> {
616        self.with_db(|db| call_hierarchy::incoming_calls(db, config, position))
617    }
618
619    /// Computes outgoing calls for the given file position.
620    pub fn outgoing_calls(
621        &self,
622        config: &CallHierarchyConfig<'_>,
623        position: FilePosition,
624    ) -> Cancellable<Option<Vec<CallItem>>> {
625        self.with_db(|db| call_hierarchy::outgoing_calls(db, config, position))
626    }
627
628    /// Returns a `mod name;` declaration which created the current module.
629    pub fn parent_module(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
630        self.with_db(|db| parent_module::parent_module(db, position))
631    }
632
633    /// Returns vec of `mod name;` declaration which are created by the current module.
634    pub fn child_modules(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
635        self.with_db(|db| child_modules::child_modules(db, position))
636    }
637
638    /// Returns crates that this file belongs to.
639    pub fn crates_for(&self, file_id: FileId) -> Cancellable<Vec<Crate>> {
640        self.with_db(|db| parent_module::crates_for(db, file_id))
641    }
642
643    /// Returns crates that this file belongs to.
644    pub fn transitive_rev_deps(&self, crate_id: Crate) -> Cancellable<Vec<Crate>> {
645        self.with_db(|db| Vec::from_iter(crate_id.transitive_rev_deps(db)))
646    }
647
648    /// Returns crates that this file *might* belong to.
649    pub fn relevant_crates_for(&self, file_id: FileId) -> Cancellable<Vec<Crate>> {
650        self.with_db(|db| db.relevant_crates(file_id).iter().copied().collect())
651    }
652
653    /// Returns the edition of the given crate.
654    pub fn crate_edition(&self, crate_id: Crate) -> Cancellable<Edition> {
655        self.with_db(|db| crate_id.data(db).edition)
656    }
657
658    /// Returns whether the given crate is a proc macro.
659    pub fn is_proc_macro_crate(&self, crate_id: Crate) -> Cancellable<bool> {
660        self.with_db(|db| crate_id.data(db).is_proc_macro)
661    }
662
663    /// Returns true if this crate has `no_std` or `no_core` specified.
664    pub fn is_crate_no_std(&self, crate_id: Crate) -> Cancellable<bool> {
665        self.with_db(|db| crate_def_map(db, crate_id).is_no_std())
666    }
667
668    /// Returns the root file of the given crate.
669    pub fn crate_root(&self, crate_id: Crate) -> Cancellable<FileId> {
670        self.with_db(|db| crate_id.data(db).root_file_id)
671    }
672
673    /// Returns the set of possible targets to run for the current file.
674    pub fn runnables(&self, file_id: FileId) -> Cancellable<Vec<Runnable>> {
675        self.with_db(|db| runnables::runnables(db, file_id))
676    }
677
678    /// Returns the set of tests for the given file position.
679    pub fn related_tests(
680        &self,
681        position: FilePosition,
682        search_scope: Option<SearchScope>,
683    ) -> Cancellable<Vec<Runnable>> {
684        let search_scope = AssertUnwindSafe(search_scope);
685        self.with_db(|db| {
686            let _ = &search_scope;
687            runnables::related_tests(db, position, search_scope.0)
688        })
689    }
690
691    /// Computes all ranges to highlight for a given item in a file.
692    pub fn highlight_related(
693        &self,
694        config: HighlightRelatedConfig,
695        position: FilePosition,
696    ) -> Cancellable<Option<Vec<HighlightedRange>>> {
697        self.with_db(|db| {
698            highlight_related::highlight_related(&Semantics::new(db), config, position)
699        })
700    }
701
702    /// Computes syntax highlighting for the given file
703    pub fn highlight(
704        &self,
705        highlight_config: HighlightConfig<'_>,
706        file_id: FileId,
707    ) -> Cancellable<Vec<HlRange>> {
708        self.with_db(|db| syntax_highlighting::highlight(db, &highlight_config, file_id, None))
709    }
710
711    /// Computes syntax highlighting for the given file range.
712    pub fn highlight_range(
713        &self,
714        highlight_config: HighlightConfig<'_>,
715        frange: FileRange,
716    ) -> Cancellable<Vec<HlRange>> {
717        self.with_db(|db| {
718            syntax_highlighting::highlight(
719                db,
720                &highlight_config,
721                frange.file_id,
722                Some(frange.range),
723            )
724        })
725    }
726
727    /// Computes syntax highlighting for the given file.
728    pub fn highlight_as_html_with_config(
729        &self,
730        config: HighlightConfig<'_>,
731        file_id: FileId,
732        rainbow: bool,
733    ) -> Cancellable<String> {
734        self.with_db(|db| {
735            syntax_highlighting::highlight_as_html_with_config(db, &config, file_id, rainbow)
736        })
737    }
738
739    /// Computes syntax highlighting for the given file.
740    pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancellable<String> {
741        self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
742    }
743
744    /// Computes completions at the given position.
745    pub fn completions(
746        &self,
747        config: &CompletionConfig<'_>,
748        position: FilePosition,
749        trigger_character: Option<char>,
750    ) -> Cancellable<Option<Vec<CompletionItem>>> {
751        self.with_db(|db| ide_completion::completions(db, config, position, trigger_character))
752    }
753
754    /// Resolves additional completion data at the position given.
755    pub fn resolve_completion_edits(
756        &self,
757        config: &CompletionConfig<'_>,
758        position: FilePosition,
759        imports: impl IntoIterator<Item = String> + std::panic::UnwindSafe,
760    ) -> Cancellable<Vec<TextEdit>> {
761        Ok(self
762            .with_db(|db| ide_completion::resolve_completion_edits(db, config, position, imports))?
763            .unwrap_or_default())
764    }
765
766    /// Computes the set of parser level diagnostics for the given file.
767    pub fn syntax_diagnostics(
768        &self,
769        config: &DiagnosticsConfig,
770        file_id: FileId,
771    ) -> Cancellable<Vec<Diagnostic>> {
772        self.with_db(|db| ide_diagnostics::syntax_diagnostics(db, config, file_id))
773    }
774
775    /// Computes the set of semantic diagnostics for the given file.
776    pub fn semantic_diagnostics(
777        &self,
778        config: &DiagnosticsConfig,
779        resolve: AssistResolveStrategy,
780        file_id: FileId,
781    ) -> Cancellable<Vec<Diagnostic>> {
782        self.with_db(|db| ide_diagnostics::semantic_diagnostics(db, config, &resolve, file_id))
783    }
784
785    /// Computes the set of both syntax and semantic diagnostics for the given file.
786    pub fn full_diagnostics(
787        &self,
788        config: &DiagnosticsConfig,
789        resolve: AssistResolveStrategy,
790        file_id: FileId,
791    ) -> Cancellable<Vec<Diagnostic>> {
792        self.with_db(|db| ide_diagnostics::full_diagnostics(db, config, &resolve, file_id))
793    }
794
795    /// Convenience function to return assists + quick fixes for diagnostics
796    pub fn assists_with_fixes(
797        &self,
798        assist_config: &AssistConfig,
799        diagnostics_config: &DiagnosticsConfig,
800        resolve: AssistResolveStrategy,
801        frange: FileRange,
802    ) -> Cancellable<Vec<Assist>> {
803        let include_fixes = match &assist_config.allowed {
804            Some(it) => it.contains(&AssistKind::QuickFix),
805            None => true,
806        };
807
808        self.with_db(|db| {
809            let diagnostic_assists = if diagnostics_config.enabled && include_fixes {
810                ide_diagnostics::full_diagnostics(db, diagnostics_config, &resolve, frange.file_id)
811                    .into_iter()
812                    .flat_map(|it| it.fixes.unwrap_or_default())
813                    .filter(|it| it.target.intersect(frange.range).is_some())
814                    .collect()
815            } else {
816                Vec::new()
817            };
818            let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
819            let assists = ide_assists::assists(db, assist_config, resolve, frange);
820
821            let mut res = diagnostic_assists;
822            res.extend(ssr_assists);
823            res.extend(assists);
824
825            res
826        })
827    }
828
829    /// Returns the edit required to rename reference at the position to the new
830    /// name.
831    pub fn rename(
832        &self,
833        position: FilePosition,
834        new_name: &str,
835        config: &RenameConfig,
836    ) -> Cancellable<Result<SourceChange, RenameError>> {
837        self.with_db(|db| rename::rename(db, position, new_name, config))
838    }
839
840    pub fn prepare_rename(
841        &self,
842        position: FilePosition,
843    ) -> Cancellable<Result<RangeInfo<()>, RenameError>> {
844        self.with_db(|db| rename::prepare_rename(db, position))
845    }
846
847    pub fn will_rename_file(
848        &self,
849        file_id: FileId,
850        new_name_stem: &str,
851    ) -> Cancellable<Option<SourceChange>> {
852        self.with_db(|db| rename::will_rename_file(db, file_id, new_name_stem))
853    }
854
855    pub fn structural_search_replace(
856        &self,
857        query: &str,
858        parse_only: bool,
859        resolve_context: FilePosition,
860        selections: Vec<FileRange>,
861    ) -> Cancellable<Result<SourceChange, SsrError>> {
862        self.with_db(|db| {
863            let rule: ide_ssr::SsrRule = query.parse()?;
864            let mut match_finder =
865                ide_ssr::MatchFinder::in_context(db, resolve_context, selections)?;
866            match_finder.add_rule(rule)?;
867            let edits = if parse_only { Default::default() } else { match_finder.edits() };
868            Ok(SourceChange::from_iter(edits))
869        })
870    }
871
872    pub fn annotations(
873        &self,
874        config: &AnnotationConfig<'_>,
875        file_id: FileId,
876    ) -> Cancellable<Vec<Annotation>> {
877        self.with_db(|db| annotations::annotations(db, config, file_id))
878    }
879
880    pub fn resolve_annotation(
881        &self,
882        config: &AnnotationConfig<'_>,
883        annotation: Annotation,
884    ) -> Cancellable<Annotation> {
885        self.with_db(|db| annotations::resolve_annotation(db, config, annotation))
886    }
887
888    pub fn move_item(
889        &self,
890        range: FileRange,
891        direction: Direction,
892    ) -> Cancellable<Option<TextEdit>> {
893        self.with_db(|db| move_item::move_item(db, range, direction))
894    }
895
896    pub fn get_recursive_memory_layout(
897        &self,
898        position: FilePosition,
899    ) -> Cancellable<Option<RecursiveMemoryLayout>> {
900        self.with_db(|db| view_memory_layout(db, position))
901    }
902
903    pub fn editioned_file_id_to_vfs(&self, file_id: hir::EditionedFileId) -> FileId {
904        file_id.file_id(&self.db)
905    }
906
907    /// Performs an operation on the database that may be canceled.
908    ///
909    /// rust-analyzer needs to be able to answer semantic questions about the
910    /// code while the code is being modified. A common problem is that a
911    /// long-running query is being calculated when a new change arrives.
912    ///
913    /// We can't just apply the change immediately: this will cause the pending
914    /// query to see inconsistent state (it will observe an absence of
915    /// repeatable read). So what we do is we **cancel** all pending queries
916    /// before applying the change.
917    ///
918    /// Salsa implements cancellation by unwinding with a special value and
919    /// catching it on the API boundary.
920    fn with_db<F, T>(&self, f: F) -> Cancellable<T>
921    where
922        F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
923    {
924        // We use `attach_db_allow_change()` and not `attach_db()` because fixture injection can change the database.
925        hir::attach_db_allow_change(&self.db, || Cancelled::catch(|| f(&self.db)))
926    }
927}
928
929#[test]
930fn analysis_is_send() {
931    fn is_send<T: Send>() {}
932    is_send::<Analysis>();
933}