rust/crates/ide/src/lib.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

753 lines
26 KiB
Rust
Raw Normal View History

2020-08-13 10:42:52 -05:00
//! ide crate provides "ide-centric" APIs for the rust-analyzer. That is,
2019-01-08 13:45:52 -06:00
//! it generally operates with files and text ranges, and returns results as
//! Strings, suitable for displaying to the human.
//!
//! What powers this API are the `RootDatabase` struct, which defines a `salsa`
2020-08-13 09:36:55 -05:00
//! database, and the `hir` crate, where majority of the analysis happens.
2019-01-08 13:33:36 -06:00
//! However, IDE specific bits of the analysis (most notably completion) happen
//! in this crate.
2019-02-03 13:15:31 -06:00
// For proving that RootDatabase is RefUnwindSafe.
#![recursion_limit = "128"]
#![warn(rust_2018_idioms, unused_lifetimes, semicolon_in_expressions_from_macros)]
2019-02-03 13:15:31 -06:00
2020-04-06 09:58:16 -05:00
#[allow(unused)]
macro_rules! eprintln {
($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
}
2020-10-02 07:26:40 -05:00
#[cfg(test)]
2020-10-02 10:34:31 -05:00
mod fixture;
2019-01-08 13:33:36 -06:00
2020-07-08 15:37:35 -05:00
mod markup;
2020-03-05 05:42:04 -06:00
mod prime_caches;
mod navigation_target;
2020-07-16 11:13:43 -05:00
2021-02-13 05:07:47 -06:00
mod annotations;
2020-07-16 11:13:43 -05:00
mod call_hierarchy;
mod signature_help;
mod doc_links;
2021-06-23 09:16:32 -05:00
mod highlight_related;
2020-07-16 11:13:43 -05:00
mod expand_macro;
mod extend_selection;
mod file_structure;
mod folding_ranges;
2021-06-22 13:43:48 -05:00
mod goto_declaration;
2019-01-11 03:53:16 -06:00
mod goto_definition;
2020-05-30 18:54:54 -05:00
mod goto_implementation;
2020-07-16 11:13:43 -05:00
mod goto_type_definition;
2019-01-08 13:33:36 -06:00
mod hover;
2020-07-16 11:13:43 -05:00
mod inlay_hints;
mod join_lines;
mod markdown_remove;
2020-07-16 11:13:43 -05:00
mod matching_brace;
2021-11-22 11:44:46 -06:00
mod moniker;
2021-03-16 07:37:00 -05:00
mod move_item;
2019-01-11 09:17:20 -06:00
mod parent_module;
2019-02-08 04:51:22 -06:00
mod references;
mod rename;
2020-07-16 11:13:43 -05:00
mod runnables;
2021-03-08 23:11:28 -06:00
mod ssr;
2021-09-08 06:35:28 -05:00
mod static_index;
2020-07-16 11:13:43 -05:00
mod status;
mod syntax_highlighting;
mod syntax_tree;
2019-03-23 06:07:21 -05:00
mod typing;
mod view_crate_graph;
mod view_hir;
mod view_mir;
2023-04-28 12:14:30 -05:00
mod interpret_function;
2021-05-21 16:59:52 -05:00
mod view_item_tree;
mod shuffle_crate_graph;
2023-04-02 19:58:20 -05:00
mod fetch_crates;
2019-01-08 13:33:36 -06:00
2023-05-02 09:12:22 -05:00
use std::ffi::OsStr;
2019-01-08 13:33:36 -06:00
2020-10-24 03:39:57 -05:00
use cfg::CfgOptions;
2023-04-02 19:58:20 -05:00
use fetch_crates::CrateInfo;
2020-08-13 09:39:16 -05:00
use ide_db::{
base_db::{
salsa::{self, ParallelDatabase},
CrateOrigin, Env, FileLoader, FileSet, SourceDatabase, VfsPath,
},
symbol_index, FxHashMap, FxIndexSet, LineIndexDatabase,
2020-02-06 05:52:32 -06:00
};
use syntax::SourceFile;
2023-05-02 09:12:22 -05:00
use triomphe::Arc;
2019-01-08 13:33:36 -06:00
use crate::navigation_target::{ToNav, TryToNav};
2019-01-08 13:33:36 -06:00
pub use crate::{
annotations::{Annotation, AnnotationConfig, AnnotationKind, AnnotationLocation},
call_hierarchy::CallItem,
2019-11-19 08:56:48 -06:00
expand_macro::ExpandedMacro,
file_structure::{StructureNode, StructureNodeKind},
2019-03-22 05:29:58 -05:00
folding_ranges::{Fold, FoldKind},
highlight_related::{HighlightRelatedConfig, HighlightedRange},
hover::{
HoverAction, HoverConfig, HoverDocFormat, HoverGotoTypeData, HoverResult,
MemoryLayoutHoverConfig, MemoryLayoutHoverRenderKind,
},
inlay_hints::{
AdjustmentHints, AdjustmentHintsMode, ClosureReturnTypeHints, DiscriminantHints, InlayHint,
InlayHintLabel, InlayHintLabelPart, InlayHintPosition, InlayHintsConfig, InlayKind,
InlayTooltip, LifetimeElisionHints,
},
join_lines::JoinLinesConfig,
2020-07-08 15:37:35 -05:00
markup::Markup,
2022-06-10 20:29:04 -05:00
moniker::{MonikerDescriptorKind, MonikerKind, MonikerResult, PackageInformation},
2021-03-16 07:37:00 -05:00
move_item::Direction,
navigation_target::NavigationTarget,
2022-01-14 03:48:59 -06:00
prime_caches::ParallelPrimeCachesProgress,
references::ReferenceSearchResult,
rename::RenameError,
runnables::{Runnable, RunnableKind, TestId},
signature_help::SignatureHelp,
static_index::{StaticIndex, StaticIndexedFile, TokenId, TokenStaticData},
2020-02-26 12:39:32 -06:00
syntax_highlighting::{
tags::{Highlight, HlMod, HlMods, HlOperator, HlPunct, HlTag},
HighlightConfig, HlRange,
2020-02-26 12:39:32 -06:00
},
2019-01-08 13:33:36 -06:00
};
pub use hir::{Documentation, Semantics};
2021-05-03 10:16:35 -05:00
pub use ide_assists::{
Assist, AssistConfig, AssistId, AssistKind, AssistResolveStrategy, SingleResolve,
};
pub use ide_completion::{
CallableSnippets, CompletionConfig, CompletionItem, CompletionItemKind, CompletionRelevance,
Snippet, SnippetScope,
};
pub use ide_db::{
2021-01-18 07:09:09 -06:00
base_db::{
2021-05-17 12:07:10 -05:00
Cancelled, Change, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange,
2021-01-18 07:09:09 -06:00
SourceRoot, SourceRootId,
},
2020-08-18 09:41:21 -05:00
label::Label,
line_index::{LineCol, LineIndex},
search::{ReferenceCategory, SearchScope},
source_change::{FileSystemEdit, SourceChange},
2020-02-06 05:52:32 -06:00
symbol_index::Query,
RootDatabase, SymbolKind,
2020-02-06 05:52:32 -06:00
};
pub use ide_diagnostics::{Diagnostic, DiagnosticsConfig, ExprFillDefaultMode, Severity};
2021-02-22 13:14:58 -06:00
pub use ide_ssr::SsrError;
pub use syntax::{TextRange, TextSize};
2020-08-12 10:03:06 -05:00
pub use text_edit::{Indel, TextEdit};
2019-01-08 13:33:36 -06:00
2021-05-17 12:07:10 -05:00
pub type Cancellable<T> = Result<T, Cancelled>;
2019-01-15 12:02:42 -06:00
2019-09-19 16:07:23 -05:00
/// Info associated with a text range.
2019-01-08 13:33:36 -06:00
#[derive(Debug)]
pub struct RangeInfo<T> {
pub range: TextRange,
pub info: T,
}
impl<T> RangeInfo<T> {
2019-01-11 05:14:09 -06:00
pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
2019-01-08 13:33:36 -06:00
RangeInfo { range, info }
}
}
/// `AnalysisHost` stores the current state of the world.
2019-06-07 12:49:29 -05:00
#[derive(Debug)]
2019-01-08 13:33:36 -06:00
pub struct AnalysisHost {
2020-02-06 05:52:32 -06:00
db: RootDatabase,
2019-01-08 13:33:36 -06:00
}
impl AnalysisHost {
2020-03-10 12:56:15 -05:00
pub fn new(lru_capacity: Option<usize>) -> AnalysisHost {
AnalysisHost { db: RootDatabase::new(lru_capacity) }
2019-06-07 12:49:29 -05:00
}
pub fn update_lru_capacity(&mut self, lru_capacity: Option<usize>) {
self.db.update_parse_query_lru_capacity(lru_capacity);
}
pub fn update_lru_capacities(&mut self, lru_capacities: &FxHashMap<Box<str>, usize>) {
self.db.update_lru_capacities(lru_capacities);
}
2019-01-08 13:33:36 -06:00
/// Returns a snapshot of the current state, which you can query for
/// semantic information.
pub fn analysis(&self) -> Analysis {
2019-02-08 05:49:43 -06:00
Analysis { db: self.db.snapshot() }
2019-01-08 13:33:36 -06:00
}
2019-01-08 13:33:36 -06:00
/// Applies changes to the current state of the world. If there are
/// outstanding snapshots, they will be canceled.
pub fn apply_change(&mut self, change: Change) {
2019-01-08 13:33:36 -06:00
self.db.apply_change(change)
}
2019-01-25 10:11:58 -06:00
2019-06-30 06:40:01 -05:00
/// NB: this clears the database
2020-08-12 09:32:36 -05:00
pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes)> {
2019-06-30 06:40:01 -05:00
self.db.per_query_memory_usage()
}
2020-01-24 09:35:37 -06:00
pub fn request_cancellation(&mut self) {
self.db.request_cancellation();
}
pub fn raw_database(&self) -> &RootDatabase {
2019-06-15 08:29:23 -05:00
&self.db
}
pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
2019-06-26 01:12:46 -05:00
&mut self.db
}
pub fn shuffle_crate_graph(&mut self) {
shuffle_crate_graph::shuffle_crate_graph(&mut self.db);
}
2019-01-08 13:33:36 -06:00
}
2020-05-06 08:26:40 -05:00
impl Default for AnalysisHost {
fn default() -> AnalysisHost {
AnalysisHost::new(None)
}
}
2019-01-08 13:33:36 -06:00
/// Analysis is a snapshot of a world state at a moment in time. It is the main
/// entry point for asking semantic information about the world. When the world
/// state is advanced using `AnalysisHost::apply_change` method, all existing
/// `Analysis` are canceled (most method return `Err(Canceled)`).
#[derive(Debug)]
pub struct Analysis {
2020-02-06 05:52:32 -06:00
db: salsa::Snapshot<RootDatabase>,
2019-01-08 13:33:36 -06:00
}
2019-02-16 05:43:59 -06:00
// As a general design guideline, `Analysis` API are intended to be independent
// from the language server protocol. That is, when exposing some functionality
// we should think in terms of "what API makes most sense" and not in terms of
// "what types LSP uses". Although currently LSP is the only consumer of the
// API, the API should in theory be usable as a library, or via a different
// protocol.
2019-01-08 13:33:36 -06:00
impl Analysis {
// Creates an analysis instance for a single file, without any external
2019-03-20 15:35:24 -05:00
// dependencies, stdlib support or ability to apply changes. See
// `AnalysisHost` for creating a fully-featured analysis.
pub fn from_single_file(text: String) -> (Analysis, FileId) {
let mut host = AnalysisHost::default();
2020-06-11 04:04:09 -05:00
let file_id = FileId(0);
let mut file_set = FileSet::default();
file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_string()));
let source_root = SourceRoot::new_local(file_set);
let mut change = Change::new();
2020-06-11 04:04:09 -05:00
change.set_roots(vec![source_root]);
2019-03-20 15:35:24 -05:00
let mut crate_graph = CrateGraph::default();
// FIXME: cfg options
// Default to enable test for single file.
let mut cfg_options = CfgOptions::default();
cfg_options.insert_atom("test".into());
2020-03-08 08:26:57 -05:00
crate_graph.add_crate_root(
file_id,
Edition::CURRENT,
2020-03-08 08:26:57 -05:00
None,
None,
cfg_options.clone(),
2023-03-31 07:10:33 -05:00
None,
2020-03-08 08:26:57 -05:00
Env::default(),
false,
2023-03-31 02:10:18 -05:00
CrateOrigin::Local { repo: None, name: None },
Err("Analysis::from_single_file has no target layout".into()),
2023-03-31 02:10:18 -05:00
None,
2020-03-08 08:26:57 -05:00
);
2023-04-22 02:48:37 -05:00
change.change_file(file_id, Some(Arc::from(text)));
2019-03-20 15:35:24 -05:00
change.set_crate_graph(crate_graph);
host.apply_change(change);
(host.analysis(), file_id)
}
2019-09-19 16:07:23 -05:00
/// Debug info about the current state of the analysis.
2021-05-17 12:07:10 -05:00
pub fn status(&self, file_id: Option<FileId>) -> Cancellable<String> {
self.with_db(|db| status::status(&*db, file_id))
2019-01-22 15:15:03 -06:00
}
2022-01-14 03:11:47 -06:00
pub fn parallel_prime_caches<F>(&self, num_worker_threads: u8, cb: F) -> Cancellable<()>
where
F: Fn(ParallelPrimeCachesProgress) + Sync + std::panic::UnwindSafe,
{
self.with_db(move |db| prime_caches::parallel_prime_caches(db, num_worker_threads, &cb))
}
2019-01-08 13:33:36 -06:00
/// Gets the text of the source file.
2023-04-22 02:48:37 -05:00
pub fn file_text(&self, file_id: FileId) -> Cancellable<Arc<str>> {
2019-07-25 12:22:41 -05:00
self.with_db(|db| db.file_text(file_id))
2019-01-08 13:33:36 -06:00
}
2019-01-08 13:33:36 -06:00
/// Gets the syntax tree of the file.
2021-05-17 12:07:10 -05:00
pub fn parse(&self, file_id: FileId) -> Cancellable<SourceFile> {
2019-07-25 12:22:41 -05:00
self.with_db(|db| db.parse(file_id).tree())
2019-01-08 13:33:36 -06:00
}
/// Returns true if this file belongs to an immutable library.
2021-05-17 12:07:10 -05:00
pub fn is_library_file(&self, file_id: FileId) -> Cancellable<bool> {
use ide_db::base_db::SourceDatabaseExt;
self.with_db(|db| db.source_root(db.file_source_root(file_id)).is_library)
}
2019-01-08 13:33:36 -06:00
/// Gets the file's `LineIndex`: data structure to convert between absolute
/// offsets and line/column representation.
2021-05-17 12:07:10 -05:00
pub fn file_line_index(&self, file_id: FileId) -> Cancellable<Arc<LineIndex>> {
2019-07-25 12:22:41 -05:00
self.with_db(|db| db.line_index(file_id))
2019-01-08 13:33:36 -06:00
}
2019-02-11 10:18:27 -06:00
/// Selects the next syntactic nodes encompassing the range.
2021-05-17 12:07:10 -05:00
pub fn extend_selection(&self, frange: FileRange) -> Cancellable<TextRange> {
self.with_db(|db| extend_selection::extend_selection(db, frange))
2019-01-08 13:33:36 -06:00
}
2019-02-11 10:18:27 -06:00
/// Returns position of the matching brace (all types of braces are
2019-01-08 13:33:36 -06:00
/// supported).
2021-05-17 12:07:10 -05:00
pub fn matching_brace(&self, position: FilePosition) -> Cancellable<Option<TextSize>> {
2019-07-25 12:22:41 -05:00
self.with_db(|db| {
let parse = db.parse(position.file_id);
let file = parse.tree();
matching_brace::matching_brace(&file, position.offset)
})
2019-01-08 13:33:36 -06:00
}
2019-01-08 13:33:36 -06:00
/// Returns a syntax tree represented as `String`, for debug purposes.
// FIXME: use a better name here.
2019-07-25 12:22:41 -05:00
pub fn syntax_tree(
&self,
file_id: FileId,
text_range: Option<TextRange>,
2021-05-17 12:07:10 -05:00
) -> Cancellable<String> {
2021-06-12 22:54:16 -05:00
self.with_db(|db| syntax_tree::syntax_tree(db, file_id, text_range))
2019-01-08 13:33:36 -06:00
}
2021-05-17 12:07:10 -05:00
pub fn view_hir(&self, position: FilePosition) -> Cancellable<String> {
2021-06-12 22:54:16 -05:00
self.with_db(|db| view_hir::view_hir(db, position))
}
pub fn view_mir(&self, position: FilePosition) -> Cancellable<String> {
self.with_db(|db| view_mir::view_mir(db, position))
}
2023-04-28 12:14:30 -05:00
pub fn interpret_function(&self, position: FilePosition) -> Cancellable<String> {
self.with_db(|db| interpret_function::interpret_function(db, position))
}
2021-05-17 12:07:10 -05:00
pub fn view_item_tree(&self, file_id: FileId) -> Cancellable<String> {
2021-06-12 22:54:16 -05:00
self.with_db(|db| view_item_tree::view_item_tree(db, file_id))
2021-05-21 16:59:52 -05:00
}
/// Renders the crate graph to GraphViz "dot" syntax.
2021-07-01 17:08:05 -05:00
pub fn view_crate_graph(&self, full: bool) -> Cancellable<Result<String, String>> {
self.with_db(|db| view_crate_graph::view_crate_graph(db, full))
}
pub fn fetch_crates(&self) -> Cancellable<FxIndexSet<CrateInfo>> {
2023-04-02 19:58:20 -05:00
self.with_db(|db| fetch_crates::fetch_crates(db))
}
2021-05-17 12:07:10 -05:00
pub fn expand_macro(&self, position: FilePosition) -> Cancellable<Option<ExpandedMacro>> {
2019-11-17 12:47:50 -06:00
self.with_db(|db| expand_macro::expand_macro(db, position))
}
2019-01-08 13:33:36 -06:00
/// Returns an edit to remove all newlines in the range, cleaning up minor
/// stuff like trailing commas.
pub fn join_lines(&self, config: &JoinLinesConfig, frange: FileRange) -> Cancellable<TextEdit> {
2019-07-25 12:22:41 -05:00
self.with_db(|db| {
let parse = db.parse(frange.file_id);
2021-10-16 06:32:55 -05:00
join_lines::join_lines(config, &parse.tree(), frange.range)
2019-07-25 12:22:41 -05:00
})
2019-01-08 13:33:36 -06:00
}
2019-01-08 13:33:36 -06:00
/// Returns an edit which should be applied when opening a new line, fixing
/// up minor stuff like continuing the comment.
2020-05-25 07:12:53 -05:00
/// The edit will be a snippet (with `$0`).
2021-05-17 12:07:10 -05:00
pub fn on_enter(&self, position: FilePosition) -> Cancellable<Option<TextEdit>> {
2021-06-12 22:54:16 -05:00
self.with_db(|db| typing::on_enter(db, position))
2019-01-08 13:33:36 -06:00
}
/// Returns an edit which should be applied after a character was typed.
///
/// This is useful for some on-the-fly fixups, like adding `;` to `let =`
/// automatically.
pub fn on_char_typed(
&self,
position: FilePosition,
char_typed: char,
autoclose: bool,
2021-05-17 12:07:10 -05:00
) -> Cancellable<Option<SourceChange>> {
2019-10-25 04:04:17 -05:00
// Fast path to not even parse the file.
if !typing::TRIGGER_CHARS.contains(char_typed) {
return Ok(None);
}
if char_typed == '<' && !autoclose {
return Ok(None);
}
2021-06-12 22:54:16 -05:00
self.with_db(|db| typing::on_char_typed(db, position, char_typed))
2019-01-08 13:33:36 -06:00
}
2019-01-08 13:33:36 -06:00
/// Returns a tree representation of symbols in the file. Useful to draw a
/// file outline.
2021-05-17 12:07:10 -05:00
pub fn file_structure(&self, file_id: FileId) -> Cancellable<Vec<StructureNode>> {
2020-07-16 11:13:43 -05:00
self.with_db(|db| file_structure::file_structure(&db.parse(file_id).tree()))
2019-01-08 13:33:36 -06:00
}
2019-07-19 16:20:09 -05:00
/// Returns a list of the places in the file where type hints can be displayed.
pub fn inlay_hints(
&self,
2020-03-31 09:02:55 -05:00
config: &InlayHintsConfig,
file_id: FileId,
range: Option<TextRange>,
2021-05-17 12:07:10 -05:00
) -> Cancellable<Vec<InlayHint>> {
2022-02-11 16:48:01 -06:00
self.with_db(|db| inlay_hints::inlay_hints(db, file_id, range, config))
2019-07-19 16:20:09 -05:00
}
2019-01-08 13:33:36 -06:00
/// Returns the set of folding ranges.
2021-05-17 12:07:10 -05:00
pub fn folding_ranges(&self, file_id: FileId) -> Cancellable<Vec<Fold>> {
2019-07-25 12:22:41 -05:00
self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
2019-01-08 13:33:36 -06:00
}
2019-01-08 13:33:36 -06:00
/// Fuzzy searches for a symbol.
2021-05-17 12:07:10 -05:00
pub fn symbol_search(&self, query: Query) -> Cancellable<Vec<NavigationTarget>> {
2019-01-10 03:20:32 -06:00
self.with_db(|db| {
2019-01-15 09:19:09 -06:00
symbol_index::world_symbols(db, query)
2021-11-27 18:42:42 -06:00
.into_iter() // xx: should we make this a par iter?
.filter_map(|s| s.try_to_nav(db))
2019-01-15 09:19:09 -06:00
.collect::<Vec<_>>()
})
2019-01-08 13:33:36 -06:00
}
2019-09-19 16:07:23 -05:00
/// Returns the definitions from the symbol at `position`.
2019-01-08 16:38:51 -06:00
pub fn goto_definition(
2019-01-08 13:33:36 -06:00
&self,
position: FilePosition,
2021-05-17 12:07:10 -05:00
) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
2019-01-20 11:55:08 -06:00
self.with_db(|db| goto_definition::goto_definition(db, position))
2019-01-08 13:33:36 -06:00
}
2021-06-22 13:43:48 -05:00
/// Returns the declaration from the symbol at `position`.
pub fn goto_declaration(
&self,
position: FilePosition,
) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
self.with_db(|db| goto_declaration::goto_declaration(db, position))
}
2019-09-19 16:07:23 -05:00
/// Returns the impls from the symbol at `position`.
pub fn goto_implementation(
&self,
position: FilePosition,
2021-05-17 12:07:10 -05:00
) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
2020-05-30 18:54:54 -05:00
self.with_db(|db| goto_implementation::goto_implementation(db, position))
}
2019-09-19 16:07:23 -05:00
/// Returns the type definitions for the symbol at `position`.
2019-04-23 13:11:27 -05:00
pub fn goto_type_definition(
&self,
position: FilePosition,
2021-05-17 12:07:10 -05:00
) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
2019-04-23 13:11:27 -05:00
self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
}
2019-01-08 13:33:36 -06:00
/// Finds all usages of the reference at point.
pub fn find_all_refs(
&self,
position: FilePosition,
search_scope: Option<SearchScope>,
) -> Cancellable<Option<Vec<ReferenceSearchResult>>> {
self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, search_scope))
2019-01-08 13:33:36 -06:00
}
2019-02-11 10:18:27 -06:00
/// Returns a short text describing element at position.
pub fn hover(
&self,
config: &HoverConfig,
range: FileRange,
) -> Cancellable<Option<RangeInfo<HoverResult>>> {
2021-07-27 16:50:26 -05:00
self.with_db(|db| hover::hover(db, range, config))
}
2021-11-22 11:44:46 -06:00
/// Returns moniker of symbol at position.
pub fn moniker(
&self,
position: FilePosition,
) -> Cancellable<Option<RangeInfo<Vec<moniker::MonikerResult>>>> {
self.with_db(|db| moniker::moniker(db, position))
}
2023-04-25 13:16:28 -05:00
/// Returns URL(s) for the documentation of the symbol under the cursor.
/// # Arguments
/// * `position` - Position in the file.
/// * `target_dir` - Directory where the build output is storeda.
2020-08-31 18:38:32 -05:00
pub fn external_docs(
2020-08-30 03:02:29 -05:00
&self,
position: FilePosition,
target_dir: Option<&OsStr>,
sysroot: Option<&OsStr>,
) -> Cancellable<doc_links::DocumentationLinks> {
self.with_db(|db| {
doc_links::external_docs(db, &position, target_dir, sysroot).unwrap_or_default()
})
2020-08-30 03:02:29 -05:00
}
/// Computes parameter information at the given position.
pub fn signature_help(&self, position: FilePosition) -> Cancellable<Option<SignatureHelp>> {
self.with_db(|db| signature_help::signature_help(db, position))
2019-01-08 13:33:36 -06:00
}
/// Computes call hierarchy candidates for the given file position.
pub fn call_hierarchy(
&self,
position: FilePosition,
2021-05-17 12:07:10 -05:00
) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
self.with_db(|db| call_hierarchy::call_hierarchy(db, position))
}
/// Computes incoming calls for the given file position.
2021-05-17 12:07:10 -05:00
pub fn incoming_calls(&self, position: FilePosition) -> Cancellable<Option<Vec<CallItem>>> {
self.with_db(|db| call_hierarchy::incoming_calls(db, position))
}
/// Computes outgoing calls for the given file position.
2021-05-17 12:07:10 -05:00
pub fn outgoing_calls(&self, position: FilePosition) -> Cancellable<Option<Vec<CallItem>>> {
self.with_db(|db| call_hierarchy::outgoing_calls(db, position))
}
2019-01-08 13:33:36 -06:00
/// Returns a `mod name;` declaration which created the current module.
2021-05-17 12:07:10 -05:00
pub fn parent_module(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
2019-01-15 12:02:42 -06:00
self.with_db(|db| parent_module::parent_module(db, position))
2019-01-08 13:33:36 -06:00
}
2019-01-08 13:33:36 -06:00
/// Returns crates this file belongs too.
pub fn crates_for(&self, file_id: FileId) -> Cancellable<Vec<CrateId>> {
self.with_db(|db| parent_module::crates_for(db, file_id))
2019-01-08 13:33:36 -06:00
}
/// Returns crates this file belongs too.
pub fn transitive_rev_deps(&self, crate_id: CrateId) -> Cancellable<Vec<CrateId>> {
self.with_db(|db| db.crate_graph().transitive_rev_deps(crate_id).collect())
}
/// Returns crates this file *might* belong too.
pub fn relevant_crates_for(&self, file_id: FileId) -> Cancellable<Vec<CrateId>> {
self.with_db(|db| db.relevant_crates(file_id).iter().copied().collect())
}
/// Returns the edition of the given crate.
2021-05-17 12:07:10 -05:00
pub fn crate_edition(&self, crate_id: CrateId) -> Cancellable<Edition> {
2020-03-09 05:11:59 -05:00
self.with_db(|db| db.crate_graph()[crate_id].edition)
}
/// Returns true if this crate has `no_std` or `no_core` specified.
pub fn is_crate_no_std(&self, crate_id: CrateId) -> Cancellable<bool> {
self.with_db(|db| hir::db::DefDatabase::crate_def_map(db, crate_id).is_no_std())
}
2019-01-08 13:33:36 -06:00
/// Returns the root file of the given crate.
2021-05-17 12:07:10 -05:00
pub fn crate_root(&self, crate_id: CrateId) -> Cancellable<FileId> {
2020-03-09 05:11:59 -05:00
self.with_db(|db| db.crate_graph()[crate_id].root_file_id)
2019-01-08 13:33:36 -06:00
}
2019-01-08 13:33:36 -06:00
/// Returns the set of possible targets to run for the current file.
2021-05-17 12:07:10 -05:00
pub fn runnables(&self, file_id: FileId) -> Cancellable<Vec<Runnable>> {
2019-01-20 11:55:08 -06:00
self.with_db(|db| runnables::runnables(db, file_id))
2019-01-08 13:33:36 -06:00
}
2021-02-27 08:59:52 -06:00
/// Returns the set of tests for the given file position.
pub fn related_tests(
&self,
position: FilePosition,
search_scope: Option<SearchScope>,
2021-05-17 12:07:10 -05:00
) -> Cancellable<Vec<Runnable>> {
2021-02-27 08:59:52 -06:00
self.with_db(|db| runnables::related_tests(db, position, search_scope))
}
/// Computes syntax highlighting for the given file
pub fn highlight(
&self,
highlight_config: HighlightConfig,
file_id: FileId,
) -> Cancellable<Vec<HlRange>> {
self.with_db(|db| syntax_highlighting::highlight(db, highlight_config, file_id, None))
2019-01-08 13:33:36 -06:00
}
/// Computes all ranges to highlight for a given item in a file.
pub fn highlight_related(
&self,
config: HighlightRelatedConfig,
position: FilePosition,
2021-06-23 18:32:56 -05:00
) -> Cancellable<Option<Vec<HighlightedRange>>> {
self.with_db(|db| {
highlight_related::highlight_related(&Semantics::new(db), config, position)
})
}
2020-02-25 07:38:50 -06:00
/// Computes syntax highlighting for the given file range.
pub fn highlight_range(
&self,
highlight_config: HighlightConfig,
frange: FileRange,
) -> Cancellable<Vec<HlRange>> {
self.with_db(|db| {
syntax_highlighting::highlight(db, highlight_config, frange.file_id, Some(frange.range))
})
2020-02-25 07:38:50 -06:00
}
2019-05-25 05:42:34 -05:00
/// Computes syntax highlighting for the given file.
2021-05-17 12:07:10 -05:00
pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancellable<String> {
2019-05-25 09:29:39 -05:00
self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
2019-05-25 05:42:34 -05:00
}
2019-01-08 13:33:36 -06:00
/// Computes completions at the given position.
pub fn completions(
&self,
2020-03-31 09:02:55 -05:00
config: &CompletionConfig,
2020-05-17 05:09:53 -05:00
position: FilePosition,
2022-05-30 07:17:58 -05:00
trigger_character: Option<char>,
2021-05-17 12:07:10 -05:00
) -> Cancellable<Option<Vec<CompletionItem>>> {
2022-05-29 10:06:48 -05:00
self.with_db(|db| {
ide_completion::completions(db, config, position, trigger_character).map(Into::into)
})
2019-01-08 13:33:36 -06:00
}
2020-12-04 08:03:22 -06:00
/// Resolves additional completion data at the position given.
pub fn resolve_completion_edits(
&self,
config: &CompletionConfig,
position: FilePosition,
imports: impl IntoIterator<Item = (String, String)> + std::panic::UnwindSafe,
2021-05-17 12:07:10 -05:00
) -> Cancellable<Vec<TextEdit>> {
2020-12-04 08:03:22 -06:00
Ok(self
.with_db(|db| ide_completion::resolve_completion_edits(db, config, position, imports))?
2020-12-04 08:03:22 -06:00
.unwrap_or_default())
}
2019-01-08 13:33:36 -06:00
/// Computes the set of diagnostics for the given file.
pub fn diagnostics(
&self,
config: &DiagnosticsConfig,
2021-05-03 09:08:09 -05:00
resolve: AssistResolveStrategy,
file_id: FileId,
2021-05-17 12:07:10 -05:00
) -> Cancellable<Vec<Diagnostic>> {
self.with_db(|db| ide_diagnostics::diagnostics(db, config, &resolve, file_id))
2019-01-08 13:33:36 -06:00
}
/// Convenience function to return assists + quick fixes for diagnostics
pub fn assists_with_fixes(
&self,
assist_config: &AssistConfig,
diagnostics_config: &DiagnosticsConfig,
2021-05-03 09:08:09 -05:00
resolve: AssistResolveStrategy,
frange: FileRange,
2021-05-17 12:07:10 -05:00
) -> Cancellable<Vec<Assist>> {
let include_fixes = match &assist_config.allowed {
Some(it) => it.iter().any(|&it| it == AssistKind::None || it == AssistKind::QuickFix),
None => true,
};
self.with_db(|db| {
2021-05-03 09:08:09 -05:00
let diagnostic_assists = if include_fixes {
ide_diagnostics::diagnostics(db, diagnostics_config, &resolve, frange.file_id)
2021-05-03 09:08:09 -05:00
.into_iter()
2021-05-17 18:11:07 -05:00
.flat_map(|it| it.fixes.unwrap_or_default())
2021-05-03 09:08:09 -05:00
.filter(|it| it.target.intersect(frange.range).is_some())
.collect()
} else {
Vec::new()
};
2021-06-15 12:55:27 -05:00
let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
let assists = ide_assists::assists(db, assist_config, resolve, frange);
2021-05-03 09:08:09 -05:00
2021-06-15 12:55:27 -05:00
let mut res = diagnostic_assists;
2021-05-03 09:08:09 -05:00
res.extend(ssr_assists.into_iter());
2021-06-15 12:55:27 -05:00
res.extend(assists.into_iter());
2021-05-03 09:08:09 -05:00
res
})
}
2019-01-08 13:33:36 -06:00
/// Returns the edit required to rename reference at the position to the new
/// name.
pub fn rename(
&self,
position: FilePosition,
new_name: &str,
2021-05-17 12:07:10 -05:00
) -> Cancellable<Result<SourceChange, RenameError>> {
self.with_db(|db| rename::rename(db, position, new_name))
2019-01-10 03:20:32 -06:00
}
2020-12-16 14:35:15 -06:00
pub fn prepare_rename(
&self,
position: FilePosition,
2021-05-17 12:07:10 -05:00
) -> Cancellable<Result<RangeInfo<()>, RenameError>> {
self.with_db(|db| rename::prepare_rename(db, position))
2020-12-16 14:35:15 -06:00
}
pub fn will_rename_file(
&self,
file_id: FileId,
new_name_stem: &str,
2021-05-17 12:07:10 -05:00
) -> Cancellable<Option<SourceChange>> {
self.with_db(|db| rename::will_rename_file(db, file_id, new_name_stem))
}
pub fn structural_search_replace(
&self,
query: &str,
2020-03-15 16:23:18 -05:00
parse_only: bool,
2020-08-13 09:45:10 -05:00
resolve_context: FilePosition,
selections: Vec<FileRange>,
2021-05-17 12:07:10 -05:00
) -> Cancellable<Result<SourceChange, SsrError>> {
self.with_db(|db| {
2021-02-22 13:14:58 -06:00
let rule: ide_ssr::SsrRule = query.parse()?;
let mut match_finder =
ide_ssr::MatchFinder::in_context(db, resolve_context, selections)?;
2020-08-13 09:45:10 -05:00
match_finder.add_rule(rule)?;
2021-01-14 11:35:22 -06:00
let edits = if parse_only { Default::default() } else { match_finder.edits() };
2020-06-08 14:44:42 -05:00
Ok(SourceChange::from(edits))
})
}
2021-02-13 05:07:47 -06:00
pub fn annotations(
&self,
config: &AnnotationConfig,
2021-02-13 05:07:47 -06:00
file_id: FileId,
2021-05-17 12:07:10 -05:00
) -> Cancellable<Vec<Annotation>> {
self.with_db(|db| annotations::annotations(db, config, file_id))
2021-02-13 05:07:47 -06:00
}
2021-05-17 12:07:10 -05:00
pub fn resolve_annotation(&self, annotation: Annotation) -> Cancellable<Annotation> {
2021-02-13 05:07:47 -06:00
self.with_db(|db| annotations::resolve_annotation(db, annotation))
}
2021-03-16 07:37:00 -05:00
pub fn move_item(
&self,
range: FileRange,
direction: Direction,
2021-05-17 12:07:10 -05:00
) -> Cancellable<Option<TextEdit>> {
2021-03-16 07:37:00 -05:00
self.with_db(|db| move_item::move_item(db, range, direction))
}
2021-05-17 12:07:10 -05:00
/// Performs an operation on the database that may be canceled.
///
/// rust-analyzer needs to be able to answer semantic questions about the
/// code while the code is being modified. A common problem is that a
/// long-running query is being calculated when a new change arrives.
///
/// We can't just apply the change immediately: this will cause the pending
/// query to see inconsistent state (it will observe an absence of
/// repeatable read). So what we do is we **cancel** all pending queries
/// before applying the change.
///
/// Salsa implements cancellation by unwinding with a special value and
2021-05-17 12:07:10 -05:00
/// catching it on the API boundary.
fn with_db<F, T>(&self, f: F) -> Cancellable<T>
2020-08-13 09:45:10 -05:00
where
F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
{
2021-05-17 12:07:10 -05:00
Cancelled::catch(|| f(&self.db))
2019-01-08 13:33:36 -06:00
}
}
#[test]
fn analysis_is_send() {
fn is_send<T: Send>() {}
is_send::<Analysis>();
}