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;
47 mod syntax_highlighting;
59 use ide_db::base_db::{
60 salsa::{self, ParallelDatabase},
61 Env, FileLoader, FileSet, SourceDatabase, VfsPath,
64 symbol_index::{self, FileSymbol},
67 use syntax::SourceFile;
69 use crate::display::ToNav;
72 annotations::{Annotation, AnnotationConfig, AnnotationKind},
73 call_hierarchy::CallItem,
74 display::navigation_target::NavigationTarget,
75 expand_macro::ExpandedMacro,
76 file_structure::{StructureNode, StructureNodeKind},
77 folding_ranges::{Fold, FoldKind},
78 hover::{HoverAction, HoverConfig, HoverGotoTypeData, HoverResult},
79 inlay_hints::{InlayHint, InlayHintsConfig, InlayKind},
82 prime_caches::PrimeCachesProgress,
83 references::ReferenceSearchResult,
85 runnables::{Runnable, RunnableKind, TestId},
86 syntax_highlighting::{
87 tags::{Highlight, HlMod, HlMods, HlOperator, HlPunct, HlTag},
91 pub use hir::{Documentation, Semantics};
92 pub use ide_assists::{
93 Assist, AssistConfig, AssistId, AssistKind, AssistResolveStrategy, SingleResolve,
95 pub use ide_completion::{
96 CompletionConfig, CompletionItem, CompletionItemKind, CompletionRelevance, ImportEdit,
101 Cancelled, Change, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange,
102 SourceRoot, SourceRootId,
106 line_index::{LineCol, LineColUtf16, LineIndex},
107 search::{ReferenceAccess, SearchScope},
108 source_change::{FileSystemEdit, SourceChange},
110 RootDatabase, SymbolKind,
112 pub use ide_diagnostics::{Diagnostic, DiagnosticsConfig, Severity};
113 pub use ide_ssr::SsrError;
114 pub use syntax::{TextRange, TextSize};
115 pub use text_edit::{Indel, TextEdit};
117 pub type Cancellable<T> = Result<T, Cancelled>;
119 /// Info associated with a text range.
121 pub struct RangeInfo<T> {
122 pub range: TextRange,
126 impl<T> RangeInfo<T> {
127 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
128 RangeInfo { range, info }
132 /// `AnalysisHost` stores the current state of the world.
134 pub struct AnalysisHost {
139 pub fn new(lru_capacity: Option<usize>) -> AnalysisHost {
140 AnalysisHost { db: RootDatabase::new(lru_capacity) }
143 pub fn update_lru_capacity(&mut self, lru_capacity: Option<usize>) {
144 self.db.update_lru_capacity(lru_capacity);
147 /// Returns a snapshot of the current state, which you can query for
148 /// semantic information.
149 pub fn analysis(&self) -> Analysis {
150 Analysis { db: self.db.snapshot() }
153 /// Applies changes to the current state of the world. If there are
154 /// outstanding snapshots, they will be canceled.
155 pub fn apply_change(&mut self, change: Change) {
156 self.db.apply_change(change)
159 pub fn collect_garbage(&mut self) {
160 self.db.collect_garbage();
162 /// NB: this clears the database
163 pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes)> {
164 self.db.per_query_memory_usage()
166 pub fn request_cancellation(&mut self) {
167 self.db.request_cancellation();
169 pub fn raw_database(&self) -> &RootDatabase {
172 pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
177 impl Default for AnalysisHost {
178 fn default() -> AnalysisHost {
179 AnalysisHost::new(None)
183 /// Analysis is a snapshot of a world state at a moment in time. It is the main
184 /// entry point for asking semantic information about the world. When the world
185 /// state is advanced using `AnalysisHost::apply_change` method, all existing
186 /// `Analysis` are canceled (most method return `Err(Canceled)`).
188 pub struct Analysis {
189 db: salsa::Snapshot<RootDatabase>,
192 // As a general design guideline, `Analysis` API are intended to be independent
193 // from the language server protocol. That is, when exposing some functionality
194 // we should think in terms of "what API makes most sense" and not in terms of
195 // "what types LSP uses". Although currently LSP is the only consumer of the
196 // API, the API should in theory be usable as a library, or via a different
199 // Creates an analysis instance for a single file, without any extenal
200 // dependencies, stdlib support or ability to apply changes. See
201 // `AnalysisHost` for creating a fully-featured analysis.
202 pub fn from_single_file(text: String) -> (Analysis, FileId) {
203 let mut host = AnalysisHost::default();
204 let file_id = FileId(0);
205 let mut file_set = FileSet::default();
206 file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_string()));
207 let source_root = SourceRoot::new_local(file_set);
209 let mut change = Change::new();
210 change.set_roots(vec![source_root]);
211 let mut crate_graph = CrateGraph::default();
212 // FIXME: cfg options
213 // Default to enable test for single file.
214 let mut cfg_options = CfgOptions::default();
215 cfg_options.insert_atom("test".into());
216 crate_graph.add_crate_root(
218 Edition::Edition2018,
225 change.change_file(file_id, Some(Arc::new(text)));
226 change.set_crate_graph(crate_graph);
227 host.apply_change(change);
228 (host.analysis(), file_id)
231 /// Debug info about the current state of the analysis.
232 pub fn status(&self, file_id: Option<FileId>) -> Cancellable<String> {
233 self.with_db(|db| status::status(&*db, file_id))
236 pub fn prime_caches<F>(&self, cb: F) -> Cancellable<()>
238 F: Fn(PrimeCachesProgress) + Sync + std::panic::UnwindSafe,
240 self.with_db(move |db| prime_caches::prime_caches(db, &cb))
243 /// Gets the text of the source file.
244 pub fn file_text(&self, file_id: FileId) -> Cancellable<Arc<String>> {
245 self.with_db(|db| db.file_text(file_id))
248 /// Gets the syntax tree of the file.
249 pub fn parse(&self, file_id: FileId) -> Cancellable<SourceFile> {
250 self.with_db(|db| db.parse(file_id).tree())
253 /// Returns true if this file belongs to an immutable library.
254 pub fn is_library_file(&self, file_id: FileId) -> Cancellable<bool> {
255 use ide_db::base_db::SourceDatabaseExt;
256 self.with_db(|db| db.source_root(db.file_source_root(file_id)).is_library)
259 /// Gets the file's `LineIndex`: data structure to convert between absolute
260 /// offsets and line/column representation.
261 pub fn file_line_index(&self, file_id: FileId) -> Cancellable<Arc<LineIndex>> {
262 self.with_db(|db| db.line_index(file_id))
265 /// Selects the next syntactic nodes encompassing the range.
266 pub fn extend_selection(&self, frange: FileRange) -> Cancellable<TextRange> {
267 self.with_db(|db| extend_selection::extend_selection(db, frange))
270 /// Returns position of the matching brace (all types of braces are
272 pub fn matching_brace(&self, position: FilePosition) -> Cancellable<Option<TextSize>> {
274 let parse = db.parse(position.file_id);
275 let file = parse.tree();
276 matching_brace::matching_brace(&file, position.offset)
280 /// Returns a syntax tree represented as `String`, for debug purposes.
281 // FIXME: use a better name here.
285 text_range: Option<TextRange>,
286 ) -> Cancellable<String> {
287 self.with_db(|db| syntax_tree::syntax_tree(db, file_id, text_range))
290 pub fn view_hir(&self, position: FilePosition) -> Cancellable<String> {
291 self.with_db(|db| view_hir::view_hir(db, position))
294 pub fn view_item_tree(&self, file_id: FileId) -> Cancellable<String> {
295 self.with_db(|db| view_item_tree::view_item_tree(db, file_id))
298 /// Renders the crate graph to GraphViz "dot" syntax.
299 pub fn view_crate_graph(&self) -> Cancellable<Result<String, String>> {
300 self.with_db(|db| view_crate_graph::view_crate_graph(db))
303 pub fn expand_macro(&self, position: FilePosition) -> Cancellable<Option<ExpandedMacro>> {
304 self.with_db(|db| expand_macro::expand_macro(db, position))
307 /// Returns an edit to remove all newlines in the range, cleaning up minor
308 /// stuff like trailing commas.
309 pub fn join_lines(&self, frange: FileRange) -> Cancellable<TextEdit> {
311 let parse = db.parse(frange.file_id);
312 join_lines::join_lines(&parse.tree(), frange.range)
316 /// Returns an edit which should be applied when opening a new line, fixing
317 /// up minor stuff like continuing the comment.
318 /// The edit will be a snippet (with `$0`).
319 pub fn on_enter(&self, position: FilePosition) -> Cancellable<Option<TextEdit>> {
320 self.with_db(|db| typing::on_enter(db, position))
323 /// Returns an edit which should be applied after a character was typed.
325 /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
327 pub fn on_char_typed(
329 position: FilePosition,
331 ) -> Cancellable<Option<SourceChange>> {
332 // Fast path to not even parse the file.
333 if !typing::TRIGGER_CHARS.contains(char_typed) {
336 self.with_db(|db| typing::on_char_typed(db, position, char_typed))
339 /// Returns a tree representation of symbols in the file. Useful to draw a
341 pub fn file_structure(&self, file_id: FileId) -> Cancellable<Vec<StructureNode>> {
342 self.with_db(|db| file_structure::file_structure(&db.parse(file_id).tree()))
345 /// Returns a list of the places in the file where type hints can be displayed.
349 config: &InlayHintsConfig,
350 ) -> Cancellable<Vec<InlayHint>> {
351 self.with_db(|db| inlay_hints::inlay_hints(db, file_id, config))
354 /// Returns the set of folding ranges.
355 pub fn folding_ranges(&self, file_id: FileId) -> Cancellable<Vec<Fold>> {
356 self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
359 /// Fuzzy searches for a symbol.
360 pub fn symbol_search(&self, query: Query) -> Cancellable<Vec<NavigationTarget>> {
362 symbol_index::world_symbols(db, query)
364 .map(|s| s.to_nav(db))
369 /// Returns the definitions from the symbol at `position`.
370 pub fn goto_definition(
372 position: FilePosition,
373 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
374 self.with_db(|db| goto_definition::goto_definition(db, position))
377 /// Returns the impls from the symbol at `position`.
378 pub fn goto_implementation(
380 position: FilePosition,
381 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
382 self.with_db(|db| goto_implementation::goto_implementation(db, position))
385 /// Returns the type definitions for the symbol at `position`.
386 pub fn goto_type_definition(
388 position: FilePosition,
389 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
390 self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
393 /// Finds all usages of the reference at point.
394 pub fn find_all_refs(
396 position: FilePosition,
397 search_scope: Option<SearchScope>,
398 ) -> Cancellable<Option<ReferenceSearchResult>> {
399 self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, search_scope))
402 /// Finds all methods and free functions for the file. Does not return tests!
403 pub fn find_all_methods(&self, file_id: FileId) -> Cancellable<Vec<FileRange>> {
404 self.with_db(|db| fn_references::find_all_methods(db, file_id))
407 /// Returns a short text describing element at position.
410 position: FilePosition,
411 links_in_hover: bool,
414 ) -> Cancellable<Option<RangeInfo<HoverResult>>> {
415 self.with_db(|db| hover::hover(db, position, links_in_hover, documentation, markdown))
418 /// Return URL(s) for the documentation of the symbol under the cursor.
419 pub fn external_docs(
421 position: FilePosition,
422 ) -> Cancellable<Option<doc_links::DocumentationLink>> {
423 self.with_db(|db| doc_links::external_docs(db, &position))
426 /// Computes parameter information for the given call expression.
427 pub fn call_info(&self, position: FilePosition) -> Cancellable<Option<CallInfo>> {
428 self.with_db(|db| ide_db::call_info::call_info(db, position))
431 /// Computes call hierarchy candidates for the given file position.
432 pub fn call_hierarchy(
434 position: FilePosition,
435 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
436 self.with_db(|db| call_hierarchy::call_hierarchy(db, position))
439 /// Computes incoming calls for the given file position.
440 pub fn incoming_calls(&self, position: FilePosition) -> Cancellable<Option<Vec<CallItem>>> {
441 self.with_db(|db| call_hierarchy::incoming_calls(db, position))
444 /// Computes incoming calls for the given file position.
445 pub fn outgoing_calls(&self, position: FilePosition) -> Cancellable<Option<Vec<CallItem>>> {
446 self.with_db(|db| call_hierarchy::outgoing_calls(db, position))
449 /// Returns a `mod name;` declaration which created the current module.
450 pub fn parent_module(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
451 self.with_db(|db| parent_module::parent_module(db, position))
454 /// Returns crates this file belongs too.
455 pub fn crate_for(&self, file_id: FileId) -> Cancellable<Vec<CrateId>> {
456 self.with_db(|db| parent_module::crate_for(db, file_id))
459 /// Returns the edition of the given crate.
460 pub fn crate_edition(&self, crate_id: CrateId) -> Cancellable<Edition> {
461 self.with_db(|db| db.crate_graph()[crate_id].edition)
464 /// Returns the root file of the given crate.
465 pub fn crate_root(&self, crate_id: CrateId) -> Cancellable<FileId> {
466 self.with_db(|db| db.crate_graph()[crate_id].root_file_id)
469 /// Returns the set of possible targets to run for the current file.
470 pub fn runnables(&self, file_id: FileId) -> Cancellable<Vec<Runnable>> {
471 self.with_db(|db| runnables::runnables(db, file_id))
474 /// Returns the set of tests for the given file position.
475 pub fn related_tests(
477 position: FilePosition,
478 search_scope: Option<SearchScope>,
479 ) -> Cancellable<Vec<Runnable>> {
480 self.with_db(|db| runnables::related_tests(db, position, search_scope))
483 /// Computes syntax highlighting for the given file
484 pub fn highlight(&self, file_id: FileId) -> Cancellable<Vec<HlRange>> {
485 self.with_db(|db| syntax_highlighting::highlight(db, file_id, None, false))
488 /// Computes syntax highlighting for the given file range.
489 pub fn highlight_range(&self, frange: FileRange) -> Cancellable<Vec<HlRange>> {
491 syntax_highlighting::highlight(db, frange.file_id, Some(frange.range), false)
495 /// Computes syntax highlighting for the given file.
496 pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancellable<String> {
497 self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
500 /// Computes completions at the given position.
503 config: &CompletionConfig,
504 position: FilePosition,
505 ) -> Cancellable<Option<Vec<CompletionItem>>> {
506 self.with_db(|db| ide_completion::completions(db, config, position).map(Into::into))
509 /// Resolves additional completion data at the position given.
510 pub fn resolve_completion_edits(
512 config: &CompletionConfig,
513 position: FilePosition,
514 full_import_path: &str,
515 imported_name: String,
516 ) -> Cancellable<Vec<TextEdit>> {
519 ide_completion::resolve_completion_edits(
527 .unwrap_or_default())
530 /// Computes assists (aka code actions aka intentions) for the given
531 /// position. If `resolve == false`, computes enough info to show the
532 /// lightbulb list in the editor, but doesn't compute actual edits, to
533 /// improve performance.
536 config: &AssistConfig,
537 resolve: AssistResolveStrategy,
539 ) -> Cancellable<Vec<Assist>> {
541 let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
542 let mut acc = ide_assists::assists(db, config, resolve, frange);
543 acc.extend(ssr_assists.into_iter());
548 /// Computes the set of diagnostics for the given file.
551 config: &DiagnosticsConfig,
552 resolve: AssistResolveStrategy,
554 ) -> Cancellable<Vec<Diagnostic>> {
555 self.with_db(|db| ide_diagnostics::diagnostics(db, config, &resolve, file_id))
558 /// Convenience function to return assists + quick fixes for diagnostics
559 pub fn assists_with_fixes(
561 assist_config: &AssistConfig,
562 diagnostics_config: &DiagnosticsConfig,
563 resolve: AssistResolveStrategy,
565 ) -> Cancellable<Vec<Assist>> {
566 let include_fixes = match &assist_config.allowed {
567 Some(it) => it.iter().any(|&it| it == AssistKind::None || it == AssistKind::QuickFix),
572 let diagnostic_assists = if include_fixes {
573 ide_diagnostics::diagnostics(db, diagnostics_config, &resolve, frange.file_id)
575 .flat_map(|it| it.fixes.unwrap_or_default())
576 .filter(|it| it.target.intersect(frange.range).is_some())
581 let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
582 let assists = ide_assists::assists(db, assist_config, resolve, frange);
584 let mut res = diagnostic_assists;
585 res.extend(ssr_assists.into_iter());
586 res.extend(assists.into_iter());
592 /// Returns the edit required to rename reference at the position to the new
596 position: FilePosition,
598 ) -> Cancellable<Result<SourceChange, RenameError>> {
599 self.with_db(|db| rename::rename(db, position, new_name))
602 pub fn prepare_rename(
604 position: FilePosition,
605 ) -> Cancellable<Result<RangeInfo<()>, RenameError>> {
606 self.with_db(|db| rename::prepare_rename(db, position))
609 pub fn will_rename_file(
613 ) -> Cancellable<Option<SourceChange>> {
614 self.with_db(|db| rename::will_rename_file(db, file_id, new_name_stem))
617 pub fn structural_search_replace(
621 resolve_context: FilePosition,
622 selections: Vec<FileRange>,
623 ) -> Cancellable<Result<SourceChange, SsrError>> {
625 let rule: ide_ssr::SsrRule = query.parse()?;
626 let mut match_finder =
627 ide_ssr::MatchFinder::in_context(db, resolve_context, selections);
628 match_finder.add_rule(rule)?;
629 let edits = if parse_only { Default::default() } else { match_finder.edits() };
630 Ok(SourceChange::from(edits))
637 config: AnnotationConfig,
638 ) -> Cancellable<Vec<Annotation>> {
639 self.with_db(|db| annotations::annotations(db, file_id, config))
642 pub fn resolve_annotation(&self, annotation: Annotation) -> Cancellable<Annotation> {
643 self.with_db(|db| annotations::resolve_annotation(db, annotation))
649 direction: Direction,
650 ) -> Cancellable<Option<TextEdit>> {
651 self.with_db(|db| move_item::move_item(db, range, direction))
654 /// Performs an operation on the database that may be canceled.
656 /// rust-analyzer needs to be able to answer semantic questions about the
657 /// code while the code is being modified. A common problem is that a
658 /// long-running query is being calculated when a new change arrives.
660 /// We can't just apply the change immediately: this will cause the pending
661 /// query to see inconsistent state (it will observe an absence of
662 /// repeatable read). So what we do is we **cancel** all pending queries
663 /// before applying the change.
665 /// Salsa implements cancelation by unwinding with a special value and
666 /// catching it on the API boundary.
667 fn with_db<F, T>(&self, f: F) -> Cancellable<T>
669 F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
671 Cancelled::catch(|| f(&self.db))
676 fn analysis_is_send() {
677 fn is_send<T: Send>() {}
678 is_send::<Analysis>();