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.
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
10 // For proving that RootDatabase is RefUnwindSafe.
11 #![recursion_limit = "128"]
14 macro_rules! eprintln {
15 ($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
32 mod goto_implementation;
33 mod goto_type_definition;
43 mod syntax_highlighting;
52 use ide_db::base_db::{
53 salsa::{self, ParallelDatabase},
54 CheckCanceled, Env, FileLoader, FileSet, SourceDatabase, VfsPath,
57 symbol_index::{self, FileSymbol},
60 use syntax::{SourceFile, TextRange, TextSize};
62 use crate::display::ToNav;
65 call_hierarchy::CallItem,
66 diagnostics::{Diagnostic, DiagnosticsConfig, Fix, Severity},
67 display::NavigationTarget,
68 expand_macro::ExpandedMacro,
69 file_structure::StructureNode,
70 folding_ranges::{Fold, FoldKind},
71 hover::{HoverAction, HoverConfig, HoverGotoTypeData, HoverResult},
72 inlay_hints::{InlayHint, InlayHintsConfig, InlayKind},
74 prime_caches::PrimeCachesProgress,
75 references::{rename::RenameError, Declaration, ReferenceSearchResult},
76 runnables::{Runnable, RunnableKind, TestId},
77 syntax_highlighting::{
78 tags::{Highlight, HighlightModifier, HighlightModifiers, HighlightTag},
83 CompletionConfig, CompletionItem, CompletionItemKind, CompletionResolveCapability,
84 CompletionScore, ImportEdit, InsertTextFormat,
88 search::{Reference, ReferenceAccess, ReferenceKind},
91 pub use assists::{Assist, AssistConfig, AssistId, AssistKind, ResolvedAssist};
92 pub use hir::{Documentation, Semantics};
93 pub use ide_db::base_db::{
94 Canceled, Change, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange, SourceRoot,
99 line_index::{LineCol, LineIndex},
101 source_change::{FileSystemEdit, SourceChange, SourceFileEdit},
105 pub use ssr::SsrError;
106 pub use text_edit::{Indel, TextEdit};
108 pub type Cancelable<T> = Result<T, Canceled>;
110 /// Info associated with a text range.
112 pub struct RangeInfo<T> {
113 pub range: TextRange,
117 impl<T> RangeInfo<T> {
118 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
119 RangeInfo { range, info }
123 /// `AnalysisHost` stores the current state of the world.
125 pub struct AnalysisHost {
130 pub fn new(lru_capacity: Option<usize>) -> AnalysisHost {
131 AnalysisHost { db: RootDatabase::new(lru_capacity) }
134 pub fn update_lru_capacity(&mut self, lru_capacity: Option<usize>) {
135 self.db.update_lru_capacity(lru_capacity);
138 /// Returns a snapshot of the current state, which you can query for
139 /// semantic information.
140 pub fn analysis(&self) -> Analysis {
141 Analysis { db: self.db.snapshot() }
144 /// Applies changes to the current state of the world. If there are
145 /// outstanding snapshots, they will be canceled.
146 pub fn apply_change(&mut self, change: Change) {
147 self.db.apply_change(change)
150 pub fn collect_garbage(&mut self) {
151 self.db.collect_garbage();
153 /// NB: this clears the database
154 pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes)> {
155 self.db.per_query_memory_usage()
157 pub fn request_cancellation(&mut self) {
158 self.db.request_cancellation();
160 pub fn raw_database(&self) -> &RootDatabase {
163 pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
168 impl Default for AnalysisHost {
169 fn default() -> AnalysisHost {
170 AnalysisHost::new(None)
174 /// Analysis is a snapshot of a world state at a moment in time. It is the main
175 /// entry point for asking semantic information about the world. When the world
176 /// state is advanced using `AnalysisHost::apply_change` method, all existing
177 /// `Analysis` are canceled (most method return `Err(Canceled)`).
179 pub struct Analysis {
180 db: salsa::Snapshot<RootDatabase>,
183 // As a general design guideline, `Analysis` API are intended to be independent
184 // from the language server protocol. That is, when exposing some functionality
185 // we should think in terms of "what API makes most sense" and not in terms of
186 // "what types LSP uses". Although currently LSP is the only consumer of the
187 // API, the API should in theory be usable as a library, or via a different
190 // Creates an analysis instance for a single file, without any extenal
191 // dependencies, stdlib support or ability to apply changes. See
192 // `AnalysisHost` for creating a fully-featured analysis.
193 pub fn from_single_file(text: String) -> (Analysis, FileId) {
194 let mut host = AnalysisHost::default();
195 let file_id = FileId(0);
196 let mut file_set = FileSet::default();
197 file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_string()));
198 let source_root = SourceRoot::new_local(file_set);
200 let mut change = Change::new();
201 change.set_roots(vec![source_root]);
202 let mut crate_graph = CrateGraph::default();
203 // FIXME: cfg options
204 // Default to enable test for single file.
205 let mut cfg_options = CfgOptions::default();
206 cfg_options.insert_atom("test".into());
207 crate_graph.add_crate_root(
209 Edition::Edition2018,
215 change.change_file(file_id, Some(Arc::new(text)));
216 change.set_crate_graph(crate_graph);
217 host.apply_change(change);
218 (host.analysis(), file_id)
221 /// Debug info about the current state of the analysis.
222 pub fn status(&self, file_id: Option<FileId>) -> Cancelable<String> {
223 self.with_db(|db| status::status(&*db, file_id))
226 pub fn prime_caches<F>(&self, cb: F) -> Cancelable<()>
228 F: Fn(PrimeCachesProgress) + Sync + std::panic::UnwindSafe,
230 self.with_db(move |db| prime_caches::prime_caches(db, &cb))
233 /// Gets the text of the source file.
234 pub fn file_text(&self, file_id: FileId) -> Cancelable<Arc<String>> {
235 self.with_db(|db| db.file_text(file_id))
238 /// Gets the syntax tree of the file.
239 pub fn parse(&self, file_id: FileId) -> Cancelable<SourceFile> {
240 self.with_db(|db| db.parse(file_id).tree())
243 /// Gets the file's `LineIndex`: data structure to convert between absolute
244 /// offsets and line/column representation.
245 pub fn file_line_index(&self, file_id: FileId) -> Cancelable<Arc<LineIndex>> {
246 self.with_db(|db| db.line_index(file_id))
249 /// Selects the next syntactic nodes encompassing the range.
250 pub fn extend_selection(&self, frange: FileRange) -> Cancelable<TextRange> {
251 self.with_db(|db| extend_selection::extend_selection(db, frange))
254 /// Returns position of the matching brace (all types of braces are
256 pub fn matching_brace(&self, position: FilePosition) -> Cancelable<Option<TextSize>> {
258 let parse = db.parse(position.file_id);
259 let file = parse.tree();
260 matching_brace::matching_brace(&file, position.offset)
264 /// Returns a syntax tree represented as `String`, for debug purposes.
265 // FIXME: use a better name here.
269 text_range: Option<TextRange>,
270 ) -> Cancelable<String> {
271 self.with_db(|db| syntax_tree::syntax_tree(&db, file_id, text_range))
274 pub fn expand_macro(&self, position: FilePosition) -> Cancelable<Option<ExpandedMacro>> {
275 self.with_db(|db| expand_macro::expand_macro(db, position))
278 /// Returns an edit to remove all newlines in the range, cleaning up minor
279 /// stuff like trailing commas.
280 pub fn join_lines(&self, frange: FileRange) -> Cancelable<TextEdit> {
282 let parse = db.parse(frange.file_id);
283 join_lines::join_lines(&parse.tree(), frange.range)
287 /// Returns an edit which should be applied when opening a new line, fixing
288 /// up minor stuff like continuing the comment.
289 /// The edit will be a snippet (with `$0`).
290 pub fn on_enter(&self, position: FilePosition) -> Cancelable<Option<TextEdit>> {
291 self.with_db(|db| typing::on_enter(&db, position))
294 /// Returns an edit which should be applied after a character was typed.
296 /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
298 pub fn on_char_typed(
300 position: FilePosition,
302 ) -> Cancelable<Option<SourceChange>> {
303 // Fast path to not even parse the file.
304 if !typing::TRIGGER_CHARS.contains(char_typed) {
307 self.with_db(|db| typing::on_char_typed(&db, position, char_typed))
310 /// Returns a tree representation of symbols in the file. Useful to draw a
312 pub fn file_structure(&self, file_id: FileId) -> Cancelable<Vec<StructureNode>> {
313 self.with_db(|db| file_structure::file_structure(&db.parse(file_id).tree()))
316 /// Returns a list of the places in the file where type hints can be displayed.
320 config: &InlayHintsConfig,
321 ) -> Cancelable<Vec<InlayHint>> {
322 self.with_db(|db| inlay_hints::inlay_hints(db, file_id, config))
325 /// Returns the set of folding ranges.
326 pub fn folding_ranges(&self, file_id: FileId) -> Cancelable<Vec<Fold>> {
327 self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
330 /// Fuzzy searches for a symbol.
331 pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
333 symbol_index::world_symbols(db, query)
335 .map(|s| s.to_nav(db))
340 /// Returns the definitions from the symbol at `position`.
341 pub fn goto_definition(
343 position: FilePosition,
344 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
345 self.with_db(|db| goto_definition::goto_definition(db, position))
348 /// Returns the impls from the symbol at `position`.
349 pub fn goto_implementation(
351 position: FilePosition,
352 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
353 self.with_db(|db| goto_implementation::goto_implementation(db, position))
356 /// Returns the type definitions for the symbol at `position`.
357 pub fn goto_type_definition(
359 position: FilePosition,
360 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
361 self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
364 /// Finds all usages of the reference at point.
365 pub fn find_all_refs(
367 position: FilePosition,
368 search_scope: Option<SearchScope>,
369 ) -> Cancelable<Option<ReferenceSearchResult>> {
371 references::find_all_refs(&Semantics::new(db), position, search_scope).map(|it| it.info)
375 /// Finds all methods and free functions for the file. Does not return tests!
376 pub fn find_all_methods(&self, file_id: FileId) -> Cancelable<Vec<FileRange>> {
377 self.with_db(|db| fn_references::find_all_methods(db, file_id))
380 /// Returns a short text describing element at position.
383 position: FilePosition,
384 links_in_hover: bool,
386 ) -> Cancelable<Option<RangeInfo<HoverResult>>> {
387 self.with_db(|db| hover::hover(db, position, links_in_hover, markdown))
390 /// Return URL(s) for the documentation of the symbol under the cursor.
391 pub fn external_docs(
393 position: FilePosition,
394 ) -> Cancelable<Option<doc_links::DocumentationLink>> {
395 self.with_db(|db| doc_links::external_docs(db, &position))
398 /// Computes parameter information for the given call expression.
399 pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
400 self.with_db(|db| ide_db::call_info::call_info(db, position))
403 /// Computes call hierarchy candidates for the given file position.
404 pub fn call_hierarchy(
406 position: FilePosition,
407 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
408 self.with_db(|db| call_hierarchy::call_hierarchy(db, position))
411 /// Computes incoming calls for the given file position.
412 pub fn incoming_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
413 self.with_db(|db| call_hierarchy::incoming_calls(db, position))
416 /// Computes incoming calls for the given file position.
417 pub fn outgoing_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
418 self.with_db(|db| call_hierarchy::outgoing_calls(db, position))
421 /// Returns a `mod name;` declaration which created the current module.
422 pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
423 self.with_db(|db| parent_module::parent_module(db, position))
426 /// Returns crates this file belongs too.
427 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
428 self.with_db(|db| parent_module::crate_for(db, file_id))
431 /// Returns the edition of the given crate.
432 pub fn crate_edition(&self, crate_id: CrateId) -> Cancelable<Edition> {
433 self.with_db(|db| db.crate_graph()[crate_id].edition)
436 /// Returns the root file of the given crate.
437 pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
438 self.with_db(|db| db.crate_graph()[crate_id].root_file_id)
441 /// Returns the set of possible targets to run for the current file.
442 pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
443 self.with_db(|db| runnables::runnables(db, file_id))
446 /// Computes syntax highlighting for the given file
447 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HighlightedRange>> {
448 self.with_db(|db| syntax_highlighting::highlight(db, file_id, None, false))
451 /// Computes syntax highlighting for the given file range.
452 pub fn highlight_range(&self, frange: FileRange) -> Cancelable<Vec<HighlightedRange>> {
454 syntax_highlighting::highlight(db, frange.file_id, Some(frange.range), false)
458 /// Computes syntax highlighting for the given file.
459 pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancelable<String> {
460 self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
463 /// Computes completions at the given position.
466 config: &CompletionConfig,
467 position: FilePosition,
468 ) -> Cancelable<Option<Vec<CompletionItem>>> {
469 self.with_db(|db| completion::completions(db, config, position).map(Into::into))
472 /// Computes resolved assists with source changes for the given position.
473 pub fn resolved_assists(
475 config: &AssistConfig,
477 ) -> Cancelable<Vec<ResolvedAssist>> {
478 self.with_db(|db| assists::Assist::resolved(db, config, frange))
481 /// Computes unresolved assists (aka code actions aka intentions) for the given
483 pub fn unresolved_assists(
485 config: &AssistConfig,
487 ) -> Cancelable<Vec<Assist>> {
488 self.with_db(|db| Assist::unresolved(db, config, frange))
491 /// Computes the set of diagnostics for the given file.
494 config: &DiagnosticsConfig,
496 ) -> Cancelable<Vec<Diagnostic>> {
497 self.with_db(|db| diagnostics::diagnostics(db, config, file_id))
500 /// Returns the edit required to rename reference at the position to the new
504 position: FilePosition,
506 ) -> Cancelable<Result<RangeInfo<SourceChange>, RenameError>> {
507 self.with_db(|db| references::rename::rename(db, position, new_name))
510 pub fn structural_search_replace(
514 resolve_context: FilePosition,
515 selections: Vec<FileRange>,
516 ) -> Cancelable<Result<SourceChange, SsrError>> {
518 let rule: ssr::SsrRule = query.parse()?;
519 let mut match_finder = ssr::MatchFinder::in_context(db, resolve_context, selections);
520 match_finder.add_rule(rule)?;
521 let edits = if parse_only { Vec::new() } else { match_finder.edits() };
522 Ok(SourceChange::from(edits))
526 /// Performs an operation on that may be Canceled.
527 fn with_db<F, T>(&self, f: F) -> Cancelable<T>
529 F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
531 self.db.catch_canceled(f)
536 fn analysis_is_send() {
537 fn is_send<T: Send>() {}
538 is_send::<Analysis>();