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;
44 mod syntax_highlighting;
53 use ide_db::base_db::{
54 salsa::{self, ParallelDatabase},
55 CheckCanceled, Env, FileLoader, FileSet, SourceDatabase, VfsPath,
58 symbol_index::{self, FileSymbol},
61 use syntax::SourceFile;
63 use crate::display::ToNav;
66 call_hierarchy::CallItem,
67 diagnostics::{Diagnostic, DiagnosticsConfig, Fix, Severity},
68 display::navigation_target::{NavigationTarget, SymbolKind},
69 expand_macro::ExpandedMacro,
70 file_structure::StructureNode,
71 folding_ranges::{Fold, FoldKind},
72 hover::{HoverAction, HoverConfig, HoverGotoTypeData, HoverResult},
73 inlay_hints::{InlayHint, InlayHintsConfig, InlayKind},
75 prime_caches::PrimeCachesProgress,
76 references::{rename::RenameError, Declaration, ReferenceSearchResult},
77 runnables::{Runnable, RunnableKind, TestId},
78 syntax_highlighting::{
79 tags::{Highlight, HighlightModifier, HighlightModifiers, HighlightTag},
83 pub use assists::{Assist, AssistConfig, AssistId, AssistKind, InsertUseConfig};
85 CompletionConfig, CompletionItem, CompletionItemKind, CompletionScore, ImportEdit,
88 pub use hir::{Documentation, Semantics};
89 pub use ide_db::base_db::{
90 Canceled, Change, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange, SourceRoot,
95 search::{Reference, ReferenceAccess, ReferenceKind},
99 line_index::{LineCol, LineIndex},
101 source_change::{FileSystemEdit, SourceChange, SourceFileEdit},
105 pub use ssr::SsrError;
106 pub use syntax::{TextRange, TextSize};
107 pub use text_edit::{Indel, TextEdit};
109 pub type Cancelable<T> = Result<T, Canceled>;
111 /// Info associated with a text range.
113 pub struct RangeInfo<T> {
114 pub range: TextRange,
118 impl<T> RangeInfo<T> {
119 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
120 RangeInfo { range, info }
124 /// `AnalysisHost` stores the current state of the world.
126 pub struct AnalysisHost {
131 pub fn new(lru_capacity: Option<usize>) -> AnalysisHost {
132 AnalysisHost { db: RootDatabase::new(lru_capacity) }
135 pub fn update_lru_capacity(&mut self, lru_capacity: Option<usize>) {
136 self.db.update_lru_capacity(lru_capacity);
139 /// Returns a snapshot of the current state, which you can query for
140 /// semantic information.
141 pub fn analysis(&self) -> Analysis {
142 Analysis { db: self.db.snapshot() }
145 /// Applies changes to the current state of the world. If there are
146 /// outstanding snapshots, they will be canceled.
147 pub fn apply_change(&mut self, change: Change) {
148 self.db.apply_change(change)
151 pub fn collect_garbage(&mut self) {
152 self.db.collect_garbage();
154 /// NB: this clears the database
155 pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes)> {
156 self.db.per_query_memory_usage()
158 pub fn request_cancellation(&mut self) {
159 self.db.request_cancellation();
161 pub fn raw_database(&self) -> &RootDatabase {
164 pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
169 impl Default for AnalysisHost {
170 fn default() -> AnalysisHost {
171 AnalysisHost::new(None)
175 /// Analysis is a snapshot of a world state at a moment in time. It is the main
176 /// entry point for asking semantic information about the world. When the world
177 /// state is advanced using `AnalysisHost::apply_change` method, all existing
178 /// `Analysis` are canceled (most method return `Err(Canceled)`).
180 pub struct Analysis {
181 db: salsa::Snapshot<RootDatabase>,
184 // As a general design guideline, `Analysis` API are intended to be independent
185 // from the language server protocol. That is, when exposing some functionality
186 // we should think in terms of "what API makes most sense" and not in terms of
187 // "what types LSP uses". Although currently LSP is the only consumer of the
188 // API, the API should in theory be usable as a library, or via a different
191 // Creates an analysis instance for a single file, without any extenal
192 // dependencies, stdlib support or ability to apply changes. See
193 // `AnalysisHost` for creating a fully-featured analysis.
194 pub fn from_single_file(text: String) -> (Analysis, FileId) {
195 let mut host = AnalysisHost::default();
196 let file_id = FileId(0);
197 let mut file_set = FileSet::default();
198 file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_string()));
199 let source_root = SourceRoot::new_local(file_set);
201 let mut change = Change::new();
202 change.set_roots(vec![source_root]);
203 let mut crate_graph = CrateGraph::default();
204 // FIXME: cfg options
205 // Default to enable test for single file.
206 let mut cfg_options = CfgOptions::default();
207 cfg_options.insert_atom("test".into());
208 crate_graph.add_crate_root(
210 Edition::Edition2018,
216 change.change_file(file_id, Some(Arc::new(text)));
217 change.set_crate_graph(crate_graph);
218 host.apply_change(change);
219 (host.analysis(), file_id)
222 /// Debug info about the current state of the analysis.
223 pub fn status(&self, file_id: Option<FileId>) -> Cancelable<String> {
224 self.with_db(|db| status::status(&*db, file_id))
227 pub fn prime_caches<F>(&self, cb: F) -> Cancelable<()>
229 F: Fn(PrimeCachesProgress) + Sync + std::panic::UnwindSafe,
231 self.with_db(move |db| prime_caches::prime_caches(db, &cb))
234 /// Gets the text of the source file.
235 pub fn file_text(&self, file_id: FileId) -> Cancelable<Arc<String>> {
236 self.with_db(|db| db.file_text(file_id))
239 /// Gets the syntax tree of the file.
240 pub fn parse(&self, file_id: FileId) -> Cancelable<SourceFile> {
241 self.with_db(|db| db.parse(file_id).tree())
244 /// Gets the file's `LineIndex`: data structure to convert between absolute
245 /// offsets and line/column representation.
246 pub fn file_line_index(&self, file_id: FileId) -> Cancelable<Arc<LineIndex>> {
247 self.with_db(|db| db.line_index(file_id))
250 /// Selects the next syntactic nodes encompassing the range.
251 pub fn extend_selection(&self, frange: FileRange) -> Cancelable<TextRange> {
252 self.with_db(|db| extend_selection::extend_selection(db, frange))
255 /// Returns position of the matching brace (all types of braces are
257 pub fn matching_brace(&self, position: FilePosition) -> Cancelable<Option<TextSize>> {
259 let parse = db.parse(position.file_id);
260 let file = parse.tree();
261 matching_brace::matching_brace(&file, position.offset)
265 /// Returns a syntax tree represented as `String`, for debug purposes.
266 // FIXME: use a better name here.
270 text_range: Option<TextRange>,
271 ) -> Cancelable<String> {
272 self.with_db(|db| syntax_tree::syntax_tree(&db, file_id, text_range))
275 pub fn view_hir(&self, position: FilePosition) -> Cancelable<String> {
276 self.with_db(|db| view_hir::view_hir(&db, position))
279 pub fn expand_macro(&self, position: FilePosition) -> Cancelable<Option<ExpandedMacro>> {
280 self.with_db(|db| expand_macro::expand_macro(db, position))
283 /// Returns an edit to remove all newlines in the range, cleaning up minor
284 /// stuff like trailing commas.
285 pub fn join_lines(&self, frange: FileRange) -> Cancelable<TextEdit> {
287 let parse = db.parse(frange.file_id);
288 join_lines::join_lines(&parse.tree(), frange.range)
292 /// Returns an edit which should be applied when opening a new line, fixing
293 /// up minor stuff like continuing the comment.
294 /// The edit will be a snippet (with `$0`).
295 pub fn on_enter(&self, position: FilePosition) -> Cancelable<Option<TextEdit>> {
296 self.with_db(|db| typing::on_enter(&db, position))
299 /// Returns an edit which should be applied after a character was typed.
301 /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
303 pub fn on_char_typed(
305 position: FilePosition,
307 ) -> Cancelable<Option<SourceChange>> {
308 // Fast path to not even parse the file.
309 if !typing::TRIGGER_CHARS.contains(char_typed) {
312 self.with_db(|db| typing::on_char_typed(&db, position, char_typed))
315 /// Returns a tree representation of symbols in the file. Useful to draw a
317 pub fn file_structure(&self, file_id: FileId) -> Cancelable<Vec<StructureNode>> {
318 self.with_db(|db| file_structure::file_structure(&db.parse(file_id).tree()))
321 /// Returns a list of the places in the file where type hints can be displayed.
325 config: &InlayHintsConfig,
326 ) -> Cancelable<Vec<InlayHint>> {
327 self.with_db(|db| inlay_hints::inlay_hints(db, file_id, config))
330 /// Returns the set of folding ranges.
331 pub fn folding_ranges(&self, file_id: FileId) -> Cancelable<Vec<Fold>> {
332 self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
335 /// Fuzzy searches for a symbol.
336 pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
338 symbol_index::world_symbols(db, query)
340 .map(|s| s.to_nav(db))
345 /// Returns the definitions from the symbol at `position`.
346 pub fn goto_definition(
348 position: FilePosition,
349 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
350 self.with_db(|db| goto_definition::goto_definition(db, position))
353 /// Returns the impls from the symbol at `position`.
354 pub fn goto_implementation(
356 position: FilePosition,
357 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
358 self.with_db(|db| goto_implementation::goto_implementation(db, position))
361 /// Returns the type definitions for the symbol at `position`.
362 pub fn goto_type_definition(
364 position: FilePosition,
365 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
366 self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
369 /// Finds all usages of the reference at point.
370 pub fn find_all_refs(
372 position: FilePosition,
373 search_scope: Option<SearchScope>,
374 ) -> Cancelable<Option<ReferenceSearchResult>> {
376 references::find_all_refs(&Semantics::new(db), position, search_scope).map(|it| it.info)
380 /// Finds all methods and free functions for the file. Does not return tests!
381 pub fn find_all_methods(&self, file_id: FileId) -> Cancelable<Vec<FileRange>> {
382 self.with_db(|db| fn_references::find_all_methods(db, file_id))
385 /// Returns a short text describing element at position.
388 position: FilePosition,
389 links_in_hover: bool,
391 ) -> Cancelable<Option<RangeInfo<HoverResult>>> {
392 self.with_db(|db| hover::hover(db, position, links_in_hover, markdown))
395 /// Return URL(s) for the documentation of the symbol under the cursor.
396 pub fn external_docs(
398 position: FilePosition,
399 ) -> Cancelable<Option<doc_links::DocumentationLink>> {
400 self.with_db(|db| doc_links::external_docs(db, &position))
403 /// Computes parameter information for the given call expression.
404 pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
405 self.with_db(|db| ide_db::call_info::call_info(db, position))
408 /// Computes call hierarchy candidates for the given file position.
409 pub fn call_hierarchy(
411 position: FilePosition,
412 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
413 self.with_db(|db| call_hierarchy::call_hierarchy(db, position))
416 /// Computes incoming calls for the given file position.
417 pub fn incoming_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
418 self.with_db(|db| call_hierarchy::incoming_calls(db, position))
421 /// Computes incoming calls for the given file position.
422 pub fn outgoing_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
423 self.with_db(|db| call_hierarchy::outgoing_calls(db, position))
426 /// Returns a `mod name;` declaration which created the current module.
427 pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
428 self.with_db(|db| parent_module::parent_module(db, position))
431 /// Returns crates this file belongs too.
432 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
433 self.with_db(|db| parent_module::crate_for(db, file_id))
436 /// Returns the edition of the given crate.
437 pub fn crate_edition(&self, crate_id: CrateId) -> Cancelable<Edition> {
438 self.with_db(|db| db.crate_graph()[crate_id].edition)
441 /// Returns the root file of the given crate.
442 pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
443 self.with_db(|db| db.crate_graph()[crate_id].root_file_id)
446 /// Returns the set of possible targets to run for the current file.
447 pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
448 self.with_db(|db| runnables::runnables(db, file_id))
451 /// Computes syntax highlighting for the given file
452 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HighlightedRange>> {
453 self.with_db(|db| syntax_highlighting::highlight(db, file_id, None, false))
456 /// Computes syntax highlighting for the given file range.
457 pub fn highlight_range(&self, frange: FileRange) -> Cancelable<Vec<HighlightedRange>> {
459 syntax_highlighting::highlight(db, frange.file_id, Some(frange.range), false)
463 /// Computes syntax highlighting for the given file.
464 pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancelable<String> {
465 self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
468 /// Computes completions at the given position.
471 config: &CompletionConfig,
472 position: FilePosition,
473 ) -> Cancelable<Option<Vec<CompletionItem>>> {
474 self.with_db(|db| completion::completions(db, config, position).map(Into::into))
477 /// Resolves additional completion data at the position given.
478 pub fn resolve_completion_edits(
480 config: &CompletionConfig,
481 position: FilePosition,
482 full_import_path: &str,
483 imported_name: String,
484 ) -> Cancelable<Vec<TextEdit>> {
487 completion::resolve_completion_edits(
495 .unwrap_or_default())
498 /// Computes assists (aka code actions aka intentions) for the given
499 /// position. If `resolve == false`, computes enough info to show the
500 /// lightbulb list in the editor, but doesn't compute actual edits, to
501 /// improve performance.
504 config: &AssistConfig,
507 ) -> Cancelable<Vec<Assist>> {
508 self.with_db(|db| Assist::get(db, config, resolve, frange))
511 /// Computes the set of diagnostics for the given file.
514 config: &DiagnosticsConfig,
516 ) -> Cancelable<Vec<Diagnostic>> {
517 self.with_db(|db| diagnostics::diagnostics(db, config, file_id))
520 /// Returns the edit required to rename reference at the position to the new
524 position: FilePosition,
526 ) -> Cancelable<Result<RangeInfo<SourceChange>, RenameError>> {
527 self.with_db(|db| references::rename::rename(db, position, new_name))
530 pub fn prepare_rename(
532 position: FilePosition,
533 ) -> Cancelable<Result<RangeInfo<()>, RenameError>> {
534 self.with_db(|db| references::rename::prepare_rename(db, position))
537 pub fn will_rename_file(
541 ) -> Cancelable<Option<SourceChange>> {
542 self.with_db(|db| references::rename::will_rename_file(db, file_id, new_name_stem))
545 pub fn structural_search_replace(
549 resolve_context: FilePosition,
550 selections: Vec<FileRange>,
551 ) -> Cancelable<Result<SourceChange, SsrError>> {
553 let rule: ssr::SsrRule = query.parse()?;
554 let mut match_finder = ssr::MatchFinder::in_context(db, resolve_context, selections);
555 match_finder.add_rule(rule)?;
556 let edits = if parse_only { Vec::new() } else { match_finder.edits() };
557 Ok(SourceChange::from(edits))
561 /// Performs an operation on that may be Canceled.
562 fn with_db<F, T>(&self, f: F) -> Cancelable<T>
564 F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
566 self.db.catch_canceled(f)
571 fn analysis_is_send() {
572 fn is_send<T: Send>() {}
573 is_send::<Analysis>();