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