1 //! ra_ide_api 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.
5 //! What powers this API are the `RootDatabase` struct, which defines a `salsa`
6 //! database, and the `ra_hir` crate, where majority of the analysis happens.
7 //! However, IDE specific bits of the analysis (most notably completion) happen
10 // For proving that RootDatabase is RefUnwindSafe.
11 #![recursion_limit = "128"]
14 pub mod mock_analysis;
24 mod goto_type_definition;
28 mod syntax_highlighting;
53 use ra_cfg::CfgOptions;
55 salsa::{self, ParallelDatabase},
56 CheckCanceled, FileLoader, SourceDatabase,
58 use ra_syntax::{SourceFile, TextRange, TextUnit};
60 use crate::{db::LineIndexDatabase, display::ToNav, symbol_index::FileSymbol};
63 assists::{Assist, AssistId},
64 change::{AnalysisChange, LibraryData},
65 completion::{CompletionItem, CompletionItemKind, InsertTextFormat},
66 diagnostics::Severity,
67 display::{file_structure, FunctionSignature, NavigationTarget, StructureNode},
68 feature_flags::FeatureFlags,
69 folding_ranges::{Fold, FoldKind},
71 inlay_hints::{InlayHint, InlayKind},
72 line_index::{LineCol, LineIndex},
73 line_index_utils::translate_offset_with_edit,
74 references::{ReferenceSearchResult, SearchScope},
75 runnables::{Runnable, RunnableKind},
76 source_change::{FileSystemEdit, SourceChange, SourceFileEdit},
77 syntax_highlighting::HighlightedRange,
80 pub use hir::Documentation;
82 Canceled, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange, SourceRootId,
85 pub type Cancelable<T> = Result<T, Canceled>;
88 pub struct Diagnostic {
91 pub fix: Option<SourceChange>,
92 pub severity: Severity,
106 pub fn new(query: String) -> Query {
107 let lowercased = query.to_lowercase();
114 limit: usize::max_value(),
118 pub fn only_types(&mut self) {
119 self.only_types = true;
122 pub fn libs(&mut self) {
126 pub fn exact(&mut self) {
130 pub fn limit(&mut self, limit: usize) {
135 /// Info associated with a text range.
137 pub struct RangeInfo<T> {
138 pub range: TextRange,
142 impl<T> RangeInfo<T> {
143 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
144 RangeInfo { range, info }
148 /// Contains information about a call site. Specifically the
149 /// `FunctionSignature`and current parameter.
151 pub struct CallInfo {
152 pub signature: FunctionSignature,
153 pub active_parameter: Option<usize>,
156 /// `AnalysisHost` stores the current state of the world.
158 pub struct AnalysisHost {
159 db: db::RootDatabase,
162 impl Default for AnalysisHost {
163 fn default() -> AnalysisHost {
164 AnalysisHost::new(None, FeatureFlags::default())
169 pub fn new(lru_capcity: Option<usize>, feature_flags: FeatureFlags) -> AnalysisHost {
170 AnalysisHost { db: db::RootDatabase::new(lru_capcity, feature_flags) }
172 /// Returns a snapshot of the current state, which you can query for
173 /// semantic information.
174 pub fn analysis(&self) -> Analysis {
175 Analysis { db: self.db.snapshot() }
178 pub fn feature_flags(&self) -> &FeatureFlags {
179 &self.db.feature_flags
182 /// Applies changes to the current state of the world. If there are
183 /// outstanding snapshots, they will be canceled.
184 pub fn apply_change(&mut self, change: AnalysisChange) {
185 self.db.apply_change(change)
188 pub fn maybe_collect_garbage(&mut self) {
189 self.db.maybe_collect_garbage();
192 pub fn collect_garbage(&mut self) {
193 self.db.collect_garbage();
195 /// NB: this clears the database
196 pub fn per_query_memory_usage(&mut self) -> Vec<(String, ra_prof::Bytes)> {
197 self.db.per_query_memory_usage()
201 ) -> &(impl hir::db::HirDatabase + salsa::Database + ra_db::SourceDatabaseExt) {
204 pub fn raw_database_mut(
206 ) -> &mut (impl hir::db::HirDatabase + salsa::Database + ra_db::SourceDatabaseExt) {
211 /// Analysis is a snapshot of a world state at a moment in time. It is the main
212 /// entry point for asking semantic information about the world. When the world
213 /// state is advanced using `AnalysisHost::apply_change` method, all existing
214 /// `Analysis` are canceled (most method return `Err(Canceled)`).
216 pub struct Analysis {
217 db: salsa::Snapshot<db::RootDatabase>,
220 // As a general design guideline, `Analysis` API are intended to be independent
221 // from the language server protocol. That is, when exposing some functionality
222 // we should think in terms of "what API makes most sense" and not in terms of
223 // "what types LSP uses". Although currently LSP is the only consumer of the
224 // API, the API should in theory be usable as a library, or via a different
227 // Creates an analysis instance for a single file, without any extenal
228 // dependencies, stdlib support or ability to apply changes. See
229 // `AnalysisHost` for creating a fully-featured analysis.
230 pub fn from_single_file(text: String) -> (Analysis, FileId) {
231 let mut host = AnalysisHost::default();
232 let source_root = SourceRootId(0);
233 let mut change = AnalysisChange::new();
234 change.add_root(source_root, true);
235 let mut crate_graph = CrateGraph::default();
236 let file_id = FileId(0);
237 // FIXME: cfg options
238 // Default to enable test for single file.
239 let mut cfg_options = CfgOptions::default();
240 cfg_options.insert_atom("test".into());
241 crate_graph.add_crate_root(file_id, Edition::Edition2018, cfg_options);
242 change.add_file(source_root, file_id, "main.rs".into(), Arc::new(text));
243 change.set_crate_graph(crate_graph);
244 host.apply_change(change);
245 (host.analysis(), file_id)
248 /// Features for Analysis.
249 pub fn feature_flags(&self) -> &FeatureFlags {
250 &self.db.feature_flags
253 /// Debug info about the current state of the analysis.
254 pub fn status(&self) -> Cancelable<String> {
255 self.with_db(|db| status::status(&*db))
258 /// Gets the text of the source file.
259 pub fn file_text(&self, file_id: FileId) -> Cancelable<Arc<String>> {
260 self.with_db(|db| db.file_text(file_id))
263 /// Gets the syntax tree of the file.
264 pub fn parse(&self, file_id: FileId) -> Cancelable<SourceFile> {
265 self.with_db(|db| db.parse(file_id).tree())
268 /// Gets the file's `LineIndex`: data structure to convert between absolute
269 /// offsets and line/column representation.
270 pub fn file_line_index(&self, file_id: FileId) -> Cancelable<Arc<LineIndex>> {
271 self.with_db(|db| db.line_index(file_id))
274 /// Selects the next syntactic nodes encompassing the range.
275 pub fn extend_selection(&self, frange: FileRange) -> Cancelable<TextRange> {
276 self.with_db(|db| extend_selection::extend_selection(db, frange))
279 /// Returns position of the matching brace (all types of braces are
281 pub fn matching_brace(&self, position: FilePosition) -> Cancelable<Option<TextUnit>> {
283 let parse = db.parse(position.file_id);
284 let file = parse.tree();
285 matching_brace::matching_brace(&file, position.offset)
289 /// Returns a syntax tree represented as `String`, for debug purposes.
290 // FIXME: use a better name here.
294 text_range: Option<TextRange>,
295 ) -> Cancelable<String> {
296 self.with_db(|db| syntax_tree::syntax_tree(&db, file_id, text_range))
299 /// Returns an edit to remove all newlines in the range, cleaning up minor
300 /// stuff like trailing commas.
301 pub fn join_lines(&self, frange: FileRange) -> Cancelable<SourceChange> {
303 let parse = db.parse(frange.file_id);
304 let file_edit = SourceFileEdit {
305 file_id: frange.file_id,
306 edit: join_lines::join_lines(&parse.tree(), frange.range),
308 SourceChange::source_file_edit("join lines", file_edit)
312 /// Returns an edit which should be applied when opening a new line, fixing
313 /// up minor stuff like continuing the comment.
314 pub fn on_enter(&self, position: FilePosition) -> Cancelable<Option<SourceChange>> {
315 self.with_db(|db| typing::on_enter(&db, position))
318 /// Returns an edit which should be applied after a character was typed.
320 /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
322 pub fn on_char_typed(
324 position: FilePosition,
326 ) -> Cancelable<Option<SourceChange>> {
327 // Fast path to not even parse the file.
328 if !typing::TRIGGER_CHARS.contains(char_typed) {
331 self.with_db(|db| typing::on_char_typed(&db, position, char_typed))
334 /// Returns a tree representation of symbols in the file. Useful to draw a
336 pub fn file_structure(&self, file_id: FileId) -> Cancelable<Vec<StructureNode>> {
337 self.with_db(|db| file_structure(&db.parse(file_id).tree()))
340 /// Returns a list of the places in the file where type hints can be displayed.
344 max_inlay_hint_length: Option<usize>,
345 ) -> Cancelable<Vec<InlayHint>> {
347 inlay_hints::inlay_hints(db, file_id, &db.parse(file_id).tree(), max_inlay_hint_length)
351 /// Returns the set of folding ranges.
352 pub fn folding_ranges(&self, file_id: FileId) -> Cancelable<Vec<Fold>> {
353 self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
356 /// Fuzzy searches for a symbol.
357 pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
359 symbol_index::world_symbols(db, query)
361 .map(|s| s.to_nav(db))
366 /// Returns the definitions from the symbol at `position`.
367 pub fn goto_definition(
369 position: FilePosition,
370 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
371 self.with_db(|db| goto_definition::goto_definition(db, position))
374 /// Returns the impls from the symbol at `position`.
375 pub fn goto_implementation(
377 position: FilePosition,
378 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
379 self.with_db(|db| impls::goto_implementation(db, position))
382 /// Returns the type definitions for the symbol at `position`.
383 pub fn goto_type_definition(
385 position: FilePosition,
386 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
387 self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
390 /// Finds all usages of the reference at point.
391 pub fn find_all_refs(
393 position: FilePosition,
394 search_scope: Option<SearchScope>,
395 ) -> Cancelable<Option<ReferenceSearchResult>> {
396 self.with_db(|db| references::find_all_refs(db, position, search_scope).map(|it| it.info))
399 /// Returns a short text describing element at position.
400 pub fn hover(&self, position: FilePosition) -> Cancelable<Option<RangeInfo<HoverResult>>> {
401 self.with_db(|db| hover::hover(db, position))
404 /// Computes parameter information for the given call expression.
405 pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
406 self.with_db(|db| call_info::call_info(db, position))
409 /// Returns a `mod name;` declaration which created the current module.
410 pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
411 self.with_db(|db| parent_module::parent_module(db, position))
414 /// Returns crates this file belongs too.
415 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
416 self.with_db(|db| parent_module::crate_for(db, file_id))
419 /// Returns the root file of the given crate.
420 pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
421 self.with_db(|db| db.crate_graph().crate_root(crate_id))
424 /// Returns the set of possible targets to run for the current file.
425 pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
426 self.with_db(|db| runnables::runnables(db, file_id))
429 /// Computes syntax highlighting for the given file.
430 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HighlightedRange>> {
431 self.with_db(|db| syntax_highlighting::highlight(db, file_id))
434 /// Computes syntax highlighting for the given file.
435 pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancelable<String> {
436 self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
439 /// Computes completions at the given position.
440 pub fn completions(&self, position: FilePosition) -> Cancelable<Option<Vec<CompletionItem>>> {
441 self.with_db(|db| completion::completions(db, position).map(Into::into))
444 /// Computes assists (aka code actions aka intentions) for the given
446 pub fn assists(&self, frange: FileRange) -> Cancelable<Vec<Assist>> {
447 self.with_db(|db| assists::assists(db, frange))
450 /// Computes the set of diagnostics for the given file.
451 pub fn diagnostics(&self, file_id: FileId) -> Cancelable<Vec<Diagnostic>> {
452 self.with_db(|db| diagnostics::diagnostics(db, file_id))
455 /// Computes the type of the expression at the given position.
456 pub fn type_of(&self, frange: FileRange) -> Cancelable<Option<String>> {
457 self.with_db(|db| hover::type_of(db, frange))
460 /// Returns the edit required to rename reference at the position to the new
464 position: FilePosition,
466 ) -> Cancelable<Option<RangeInfo<SourceChange>>> {
467 self.with_db(|db| references::rename(db, position, new_name))
470 /// Performs an operation on that may be Canceled.
471 fn with_db<F: FnOnce(&db::RootDatabase) -> T + std::panic::UnwindSafe, T>(
475 self.db.catch_canceled(f)
480 fn analysis_is_send() {
481 fn is_send<T: Send>() {}
482 is_send::<Analysis>();