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)*) };
28 mod highlight_references;
35 mod goto_implementation;
36 mod goto_type_definition;
49 mod syntax_highlighting;
60 use ide_db::base_db::{
61 salsa::{self, ParallelDatabase},
62 Env, FileLoader, FileSet, SourceDatabase, VfsPath,
65 symbol_index::{self, FileSymbol},
68 use syntax::SourceFile;
70 use crate::display::ToNav;
73 annotations::{Annotation, AnnotationConfig, AnnotationKind},
74 call_hierarchy::CallItem,
75 display::navigation_target::NavigationTarget,
76 expand_macro::ExpandedMacro,
77 file_structure::{StructureNode, StructureNodeKind},
78 folding_ranges::{Fold, FoldKind},
79 highlight_references::DocumentHighlight,
80 hover::{HoverAction, HoverConfig, HoverDocFormat, HoverGotoTypeData, HoverResult},
81 inlay_hints::{InlayHint, InlayHintsConfig, InlayKind},
84 prime_caches::PrimeCachesProgress,
85 references::ReferenceSearchResult,
87 runnables::{Runnable, RunnableKind, TestId},
88 syntax_highlighting::{
89 tags::{Highlight, HlMod, HlMods, HlOperator, HlPunct, HlTag},
93 pub use hir::{Documentation, Semantics};
94 pub use ide_assists::{
95 Assist, AssistConfig, AssistId, AssistKind, AssistResolveStrategy, SingleResolve,
97 pub use ide_completion::{
98 CompletionConfig, CompletionItem, CompletionItemKind, CompletionRelevance, ImportEdit,
103 Cancelled, Change, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange,
104 SourceRoot, SourceRootId,
108 line_index::{LineCol, LineColUtf16, LineIndex},
109 search::{ReferenceAccess, SearchScope},
110 source_change::{FileSystemEdit, SourceChange},
112 RootDatabase, SymbolKind,
114 pub use ide_diagnostics::{Diagnostic, DiagnosticsConfig, Severity};
115 pub use ide_ssr::SsrError;
116 pub use syntax::{TextRange, TextSize};
117 pub use text_edit::{Indel, TextEdit};
119 pub type Cancellable<T> = Result<T, Cancelled>;
121 /// Info associated with a text range.
123 pub struct RangeInfo<T> {
124 pub range: TextRange,
128 impl<T> RangeInfo<T> {
129 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
130 RangeInfo { range, info }
134 /// `AnalysisHost` stores the current state of the world.
136 pub struct AnalysisHost {
141 pub fn new(lru_capacity: Option<usize>) -> AnalysisHost {
142 AnalysisHost { db: RootDatabase::new(lru_capacity) }
145 pub fn update_lru_capacity(&mut self, lru_capacity: Option<usize>) {
146 self.db.update_lru_capacity(lru_capacity);
149 /// Returns a snapshot of the current state, which you can query for
150 /// semantic information.
151 pub fn analysis(&self) -> Analysis {
152 Analysis { db: self.db.snapshot() }
155 /// Applies changes to the current state of the world. If there are
156 /// outstanding snapshots, they will be canceled.
157 pub fn apply_change(&mut self, change: Change) {
158 self.db.apply_change(change)
161 pub fn collect_garbage(&mut self) {
162 self.db.collect_garbage();
164 /// NB: this clears the database
165 pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes)> {
166 self.db.per_query_memory_usage()
168 pub fn request_cancellation(&mut self) {
169 self.db.request_cancellation();
171 pub fn raw_database(&self) -> &RootDatabase {
174 pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
179 impl Default for AnalysisHost {
180 fn default() -> AnalysisHost {
181 AnalysisHost::new(None)
185 /// Analysis is a snapshot of a world state at a moment in time. It is the main
186 /// entry point for asking semantic information about the world. When the world
187 /// state is advanced using `AnalysisHost::apply_change` method, all existing
188 /// `Analysis` are canceled (most method return `Err(Canceled)`).
190 pub struct Analysis {
191 db: salsa::Snapshot<RootDatabase>,
194 // As a general design guideline, `Analysis` API are intended to be independent
195 // from the language server protocol. That is, when exposing some functionality
196 // we should think in terms of "what API makes most sense" and not in terms of
197 // "what types LSP uses". Although currently LSP is the only consumer of the
198 // API, the API should in theory be usable as a library, or via a different
201 // Creates an analysis instance for a single file, without any extenal
202 // dependencies, stdlib support or ability to apply changes. See
203 // `AnalysisHost` for creating a fully-featured analysis.
204 pub fn from_single_file(text: String) -> (Analysis, FileId) {
205 let mut host = AnalysisHost::default();
206 let file_id = FileId(0);
207 let mut file_set = FileSet::default();
208 file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_string()));
209 let source_root = SourceRoot::new_local(file_set);
211 let mut change = Change::new();
212 change.set_roots(vec![source_root]);
213 let mut crate_graph = CrateGraph::default();
214 // FIXME: cfg options
215 // Default to enable test for single file.
216 let mut cfg_options = CfgOptions::default();
217 cfg_options.insert_atom("test".into());
218 crate_graph.add_crate_root(
220 Edition::Edition2018,
227 change.change_file(file_id, Some(Arc::new(text)));
228 change.set_crate_graph(crate_graph);
229 host.apply_change(change);
230 (host.analysis(), file_id)
233 /// Debug info about the current state of the analysis.
234 pub fn status(&self, file_id: Option<FileId>) -> Cancellable<String> {
235 self.with_db(|db| status::status(&*db, file_id))
238 pub fn prime_caches<F>(&self, cb: F) -> Cancellable<()>
240 F: Fn(PrimeCachesProgress) + Sync + std::panic::UnwindSafe,
242 self.with_db(move |db| prime_caches::prime_caches(db, &cb))
245 /// Gets the text of the source file.
246 pub fn file_text(&self, file_id: FileId) -> Cancellable<Arc<String>> {
247 self.with_db(|db| db.file_text(file_id))
250 /// Gets the syntax tree of the file.
251 pub fn parse(&self, file_id: FileId) -> Cancellable<SourceFile> {
252 self.with_db(|db| db.parse(file_id).tree())
255 /// Returns true if this file belongs to an immutable library.
256 pub fn is_library_file(&self, file_id: FileId) -> Cancellable<bool> {
257 use ide_db::base_db::SourceDatabaseExt;
258 self.with_db(|db| db.source_root(db.file_source_root(file_id)).is_library)
261 /// Gets the file's `LineIndex`: data structure to convert between absolute
262 /// offsets and line/column representation.
263 pub fn file_line_index(&self, file_id: FileId) -> Cancellable<Arc<LineIndex>> {
264 self.with_db(|db| db.line_index(file_id))
267 /// Selects the next syntactic nodes encompassing the range.
268 pub fn extend_selection(&self, frange: FileRange) -> Cancellable<TextRange> {
269 self.with_db(|db| extend_selection::extend_selection(db, frange))
272 /// Returns position of the matching brace (all types of braces are
274 pub fn matching_brace(&self, position: FilePosition) -> Cancellable<Option<TextSize>> {
276 let parse = db.parse(position.file_id);
277 let file = parse.tree();
278 matching_brace::matching_brace(&file, position.offset)
282 /// Returns a syntax tree represented as `String`, for debug purposes.
283 // FIXME: use a better name here.
287 text_range: Option<TextRange>,
288 ) -> Cancellable<String> {
289 self.with_db(|db| syntax_tree::syntax_tree(db, file_id, text_range))
292 pub fn view_hir(&self, position: FilePosition) -> Cancellable<String> {
293 self.with_db(|db| view_hir::view_hir(db, position))
296 pub fn view_item_tree(&self, file_id: FileId) -> Cancellable<String> {
297 self.with_db(|db| view_item_tree::view_item_tree(db, file_id))
300 /// Renders the crate graph to GraphViz "dot" syntax.
301 pub fn view_crate_graph(&self) -> Cancellable<Result<String, String>> {
302 self.with_db(|db| view_crate_graph::view_crate_graph(db))
305 pub fn expand_macro(&self, position: FilePosition) -> Cancellable<Option<ExpandedMacro>> {
306 self.with_db(|db| expand_macro::expand_macro(db, position))
309 /// Returns an edit to remove all newlines in the range, cleaning up minor
310 /// stuff like trailing commas.
311 pub fn join_lines(&self, frange: FileRange) -> Cancellable<TextEdit> {
313 let parse = db.parse(frange.file_id);
314 join_lines::join_lines(&parse.tree(), frange.range)
318 /// Returns an edit which should be applied when opening a new line, fixing
319 /// up minor stuff like continuing the comment.
320 /// The edit will be a snippet (with `$0`).
321 pub fn on_enter(&self, position: FilePosition) -> Cancellable<Option<TextEdit>> {
322 self.with_db(|db| typing::on_enter(db, position))
325 /// Returns an edit which should be applied after a character was typed.
327 /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
329 pub fn on_char_typed(
331 position: FilePosition,
333 ) -> Cancellable<Option<SourceChange>> {
334 // Fast path to not even parse the file.
335 if !typing::TRIGGER_CHARS.contains(char_typed) {
338 self.with_db(|db| typing::on_char_typed(db, position, char_typed))
341 /// Returns a tree representation of symbols in the file. Useful to draw a
343 pub fn file_structure(&self, file_id: FileId) -> Cancellable<Vec<StructureNode>> {
344 self.with_db(|db| file_structure::file_structure(&db.parse(file_id).tree()))
347 /// Returns a list of the places in the file where type hints can be displayed.
351 config: &InlayHintsConfig,
352 ) -> Cancellable<Vec<InlayHint>> {
353 self.with_db(|db| inlay_hints::inlay_hints(db, file_id, config))
356 /// Returns the set of folding ranges.
357 pub fn folding_ranges(&self, file_id: FileId) -> Cancellable<Vec<Fold>> {
358 self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
361 /// Fuzzy searches for a symbol.
362 pub fn symbol_search(&self, query: Query) -> Cancellable<Vec<NavigationTarget>> {
364 symbol_index::world_symbols(db, query)
366 .map(|s| s.to_nav(db))
371 /// Returns the definitions from the symbol at `position`.
372 pub fn goto_definition(
374 position: FilePosition,
375 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
376 self.with_db(|db| goto_definition::goto_definition(db, position))
379 /// Returns the impls from the symbol at `position`.
380 pub fn goto_implementation(
382 position: FilePosition,
383 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
384 self.with_db(|db| goto_implementation::goto_implementation(db, position))
387 /// Returns the type definitions for the symbol at `position`.
388 pub fn goto_type_definition(
390 position: FilePosition,
391 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
392 self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
395 /// Finds all usages of the reference at point.
396 pub fn find_all_refs(
398 position: FilePosition,
399 search_scope: Option<SearchScope>,
400 ) -> Cancellable<Option<ReferenceSearchResult>> {
401 self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, search_scope))
404 /// Finds all methods and free functions for the file. Does not return tests!
405 pub fn find_all_methods(&self, file_id: FileId) -> Cancellable<Vec<FileRange>> {
406 self.with_db(|db| fn_references::find_all_methods(db, file_id))
409 /// Returns a short text describing element at position.
412 position: FilePosition,
413 config: &HoverConfig,
414 ) -> Cancellable<Option<RangeInfo<HoverResult>>> {
415 self.with_db(|db| hover::hover(db, position, config))
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 outgoing 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 all ranges to highlight for a given item in a file.
489 pub fn highlight_related(
491 position: FilePosition,
492 ) -> Cancellable<Option<Vec<DocumentHighlight>>> {
493 self.with_db(|db| highlight_references::highlight_related(&Semantics::new(db), position))
496 /// Computes syntax highlighting for the given file range.
497 pub fn highlight_range(&self, frange: FileRange) -> Cancellable<Vec<HlRange>> {
499 syntax_highlighting::highlight(db, frange.file_id, Some(frange.range), false)
503 /// Computes syntax highlighting for the given file.
504 pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancellable<String> {
505 self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
508 /// Computes completions at the given position.
511 config: &CompletionConfig,
512 position: FilePosition,
513 ) -> Cancellable<Option<Vec<CompletionItem>>> {
514 self.with_db(|db| ide_completion::completions(db, config, position).map(Into::into))
517 /// Resolves additional completion data at the position given.
518 pub fn resolve_completion_edits(
520 config: &CompletionConfig,
521 position: FilePosition,
522 full_import_path: &str,
523 imported_name: String,
524 ) -> Cancellable<Vec<TextEdit>> {
527 ide_completion::resolve_completion_edits(
535 .unwrap_or_default())
538 /// Computes assists (aka code actions aka intentions) for the given
539 /// position. If `resolve == false`, computes enough info to show the
540 /// lightbulb list in the editor, but doesn't compute actual edits, to
541 /// improve performance.
544 config: &AssistConfig,
545 resolve: AssistResolveStrategy,
547 ) -> Cancellable<Vec<Assist>> {
549 let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
550 let mut acc = ide_assists::assists(db, config, resolve, frange);
551 acc.extend(ssr_assists.into_iter());
556 /// Computes the set of diagnostics for the given file.
559 config: &DiagnosticsConfig,
560 resolve: AssistResolveStrategy,
562 ) -> Cancellable<Vec<Diagnostic>> {
563 self.with_db(|db| ide_diagnostics::diagnostics(db, config, &resolve, file_id))
566 /// Convenience function to return assists + quick fixes for diagnostics
567 pub fn assists_with_fixes(
569 assist_config: &AssistConfig,
570 diagnostics_config: &DiagnosticsConfig,
571 resolve: AssistResolveStrategy,
573 ) -> Cancellable<Vec<Assist>> {
574 let include_fixes = match &assist_config.allowed {
575 Some(it) => it.iter().any(|&it| it == AssistKind::None || it == AssistKind::QuickFix),
580 let diagnostic_assists = if include_fixes {
581 ide_diagnostics::diagnostics(db, diagnostics_config, &resolve, frange.file_id)
583 .flat_map(|it| it.fixes.unwrap_or_default())
584 .filter(|it| it.target.intersect(frange.range).is_some())
589 let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
590 let assists = ide_assists::assists(db, assist_config, resolve, frange);
592 let mut res = diagnostic_assists;
593 res.extend(ssr_assists.into_iter());
594 res.extend(assists.into_iter());
600 /// Returns the edit required to rename reference at the position to the new
604 position: FilePosition,
606 ) -> Cancellable<Result<SourceChange, RenameError>> {
607 self.with_db(|db| rename::rename(db, position, new_name))
610 pub fn prepare_rename(
612 position: FilePosition,
613 ) -> Cancellable<Result<RangeInfo<()>, RenameError>> {
614 self.with_db(|db| rename::prepare_rename(db, position))
617 pub fn will_rename_file(
621 ) -> Cancellable<Option<SourceChange>> {
622 self.with_db(|db| rename::will_rename_file(db, file_id, new_name_stem))
625 pub fn structural_search_replace(
629 resolve_context: FilePosition,
630 selections: Vec<FileRange>,
631 ) -> Cancellable<Result<SourceChange, SsrError>> {
633 let rule: ide_ssr::SsrRule = query.parse()?;
634 let mut match_finder =
635 ide_ssr::MatchFinder::in_context(db, resolve_context, selections);
636 match_finder.add_rule(rule)?;
637 let edits = if parse_only { Default::default() } else { match_finder.edits() };
638 Ok(SourceChange::from(edits))
645 config: AnnotationConfig,
646 ) -> Cancellable<Vec<Annotation>> {
647 self.with_db(|db| annotations::annotations(db, file_id, config))
650 pub fn resolve_annotation(&self, annotation: Annotation) -> Cancellable<Annotation> {
651 self.with_db(|db| annotations::resolve_annotation(db, annotation))
657 direction: Direction,
658 ) -> Cancellable<Option<TextEdit>> {
659 self.with_db(|db| move_item::move_item(db, range, direction))
662 /// Performs an operation on the database that may be canceled.
664 /// rust-analyzer needs to be able to answer semantic questions about the
665 /// code while the code is being modified. A common problem is that a
666 /// long-running query is being calculated when a new change arrives.
668 /// We can't just apply the change immediately: this will cause the pending
669 /// query to see inconsistent state (it will observe an absence of
670 /// repeatable read). So what we do is we **cancel** all pending queries
671 /// before applying the change.
673 /// Salsa implements cancelation by unwinding with a special value and
674 /// catching it on the API boundary.
675 fn with_db<F, T>(&self, f: F) -> Cancellable<T>
677 F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
679 Cancelled::catch(|| f(&self.db))
684 fn analysis_is_send() {
685 fn is_send<T: Send>() {}
686 is_send::<Analysis>();