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)*) };
23 mod navigation_target;
29 mod highlight_related;
37 mod goto_implementation;
38 mod goto_type_definition;
53 mod syntax_highlighting;
59 mod shuffle_crate_graph;
66 salsa::{self, ParallelDatabase},
67 Env, FileLoader, FileSet, SourceDatabase, VfsPath,
69 symbol_index, LineIndexDatabase,
71 use syntax::SourceFile;
73 use crate::navigation_target::{ToNav, TryToNav};
76 annotations::{Annotation, AnnotationConfig, AnnotationKind},
77 call_hierarchy::CallItem,
79 expand_macro::ExpandedMacro,
80 file_structure::{StructureNode, StructureNodeKind},
81 folding_ranges::{Fold, FoldKind},
82 highlight_related::{HighlightRelatedConfig, HighlightedRange},
83 hover::{HoverAction, HoverConfig, HoverDocFormat, HoverGotoTypeData, HoverResult},
84 inlay_hints::{InlayHint, InlayHintsConfig, InlayKind},
85 join_lines::JoinLinesConfig,
87 moniker::{MonikerKind, MonikerResult, PackageInformation},
89 navigation_target::NavigationTarget,
90 prime_caches::{ParallelPrimeCachesProgress, PrimeCachesProgress},
91 references::ReferenceSearchResult,
93 runnables::{Runnable, RunnableKind, TestId},
94 static_index::{StaticIndex, StaticIndexedFile, TokenId, TokenStaticData},
95 syntax_highlighting::{
96 tags::{Highlight, HlMod, HlMods, HlOperator, HlPunct, HlTag},
100 pub use hir::{Documentation, Semantics};
101 pub use ide_assists::{
102 Assist, AssistConfig, AssistId, AssistKind, AssistResolveStrategy, SingleResolve,
104 pub use ide_completion::{
105 CompletionConfig, CompletionItem, CompletionItemKind, CompletionRelevance, ImportEdit, Snippet,
110 Cancelled, Change, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange,
111 SourceRoot, SourceRootId,
114 line_index::{LineCol, LineColUtf16, LineIndex},
115 search::{ReferenceCategory, SearchScope},
116 source_change::{FileSystemEdit, SourceChange},
118 RootDatabase, SymbolKind,
120 pub use ide_diagnostics::{Diagnostic, DiagnosticsConfig, ExprFillDefaultMode, Severity};
121 pub use ide_ssr::SsrError;
122 pub use syntax::{TextRange, TextSize};
123 pub use text_edit::{Indel, TextEdit};
125 pub type Cancellable<T> = Result<T, Cancelled>;
127 /// Info associated with a text range.
129 pub struct RangeInfo<T> {
130 pub range: TextRange,
134 impl<T> RangeInfo<T> {
135 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
136 RangeInfo { range, info }
140 /// `AnalysisHost` stores the current state of the world.
142 pub struct AnalysisHost {
147 pub fn new(lru_capacity: Option<usize>) -> AnalysisHost {
148 AnalysisHost { db: RootDatabase::new(lru_capacity) }
151 pub fn update_lru_capacity(&mut self, lru_capacity: Option<usize>) {
152 self.db.update_lru_capacity(lru_capacity);
155 /// Returns a snapshot of the current state, which you can query for
156 /// semantic information.
157 pub fn analysis(&self) -> Analysis {
158 Analysis { db: self.db.snapshot() }
161 /// Applies changes to the current state of the world. If there are
162 /// outstanding snapshots, they will be canceled.
163 pub fn apply_change(&mut self, change: Change) {
164 self.db.apply_change(change)
167 /// NB: this clears the database
168 pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes)> {
169 self.db.per_query_memory_usage()
171 pub fn request_cancellation(&mut self) {
172 self.db.request_cancellation();
174 pub fn raw_database(&self) -> &RootDatabase {
177 pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
181 pub fn shuffle_crate_graph(&mut self) {
182 shuffle_crate_graph::shuffle_crate_graph(&mut self.db);
186 impl Default for AnalysisHost {
187 fn default() -> AnalysisHost {
188 AnalysisHost::new(None)
192 /// Analysis is a snapshot of a world state at a moment in time. It is the main
193 /// entry point for asking semantic information about the world. When the world
194 /// state is advanced using `AnalysisHost::apply_change` method, all existing
195 /// `Analysis` are canceled (most method return `Err(Canceled)`).
197 pub struct Analysis {
198 db: salsa::Snapshot<RootDatabase>,
201 // As a general design guideline, `Analysis` API are intended to be independent
202 // from the language server protocol. That is, when exposing some functionality
203 // we should think in terms of "what API makes most sense" and not in terms of
204 // "what types LSP uses". Although currently LSP is the only consumer of the
205 // API, the API should in theory be usable as a library, or via a different
208 // Creates an analysis instance for a single file, without any extenal
209 // dependencies, stdlib support or ability to apply changes. See
210 // `AnalysisHost` for creating a fully-featured analysis.
211 pub fn from_single_file(text: String) -> (Analysis, FileId) {
212 let mut host = AnalysisHost::default();
213 let file_id = FileId(0);
214 let mut file_set = FileSet::default();
215 file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_string()));
216 let source_root = SourceRoot::new_local(file_set);
218 let mut change = Change::new();
219 change.set_roots(vec![source_root]);
220 let mut crate_graph = CrateGraph::default();
221 // FIXME: cfg options
222 // Default to enable test for single file.
223 let mut cfg_options = CfgOptions::default();
224 cfg_options.insert_atom("test".into());
225 crate_graph.add_crate_root(
236 change.change_file(file_id, Some(Arc::new(text)));
237 change.set_crate_graph(crate_graph);
238 host.apply_change(change);
239 (host.analysis(), file_id)
242 /// Debug info about the current state of the analysis.
243 pub fn status(&self, file_id: Option<FileId>) -> Cancellable<String> {
244 self.with_db(|db| status::status(&*db, file_id))
247 pub fn prime_caches<F>(&self, cb: F) -> Cancellable<()>
249 F: Fn(PrimeCachesProgress) + Sync + std::panic::UnwindSafe,
251 self.with_db(move |db| prime_caches::prime_caches(db, &cb))
254 pub fn parallel_prime_caches<F>(&self, num_worker_threads: u8, cb: F) -> Cancellable<()>
256 F: Fn(ParallelPrimeCachesProgress) + Sync + std::panic::UnwindSafe,
258 self.with_db(move |db| prime_caches::parallel_prime_caches(db, num_worker_threads, &cb))
261 /// Gets the text of the source file.
262 pub fn file_text(&self, file_id: FileId) -> Cancellable<Arc<String>> {
263 self.with_db(|db| db.file_text(file_id))
266 /// Gets the syntax tree of the file.
267 pub fn parse(&self, file_id: FileId) -> Cancellable<SourceFile> {
268 self.with_db(|db| db.parse(file_id).tree())
271 /// Returns true if this file belongs to an immutable library.
272 pub fn is_library_file(&self, file_id: FileId) -> Cancellable<bool> {
273 use ide_db::base_db::SourceDatabaseExt;
274 self.with_db(|db| db.source_root(db.file_source_root(file_id)).is_library)
277 /// Gets the file's `LineIndex`: data structure to convert between absolute
278 /// offsets and line/column representation.
279 pub fn file_line_index(&self, file_id: FileId) -> Cancellable<Arc<LineIndex>> {
280 self.with_db(|db| db.line_index(file_id))
283 /// Selects the next syntactic nodes encompassing the range.
284 pub fn extend_selection(&self, frange: FileRange) -> Cancellable<TextRange> {
285 self.with_db(|db| extend_selection::extend_selection(db, frange))
288 /// Returns position of the matching brace (all types of braces are
290 pub fn matching_brace(&self, position: FilePosition) -> Cancellable<Option<TextSize>> {
292 let parse = db.parse(position.file_id);
293 let file = parse.tree();
294 matching_brace::matching_brace(&file, position.offset)
298 /// Returns a syntax tree represented as `String`, for debug purposes.
299 // FIXME: use a better name here.
303 text_range: Option<TextRange>,
304 ) -> Cancellable<String> {
305 self.with_db(|db| syntax_tree::syntax_tree(db, file_id, text_range))
308 pub fn view_hir(&self, position: FilePosition) -> Cancellable<String> {
309 self.with_db(|db| view_hir::view_hir(db, position))
312 pub fn view_item_tree(&self, file_id: FileId) -> Cancellable<String> {
313 self.with_db(|db| view_item_tree::view_item_tree(db, file_id))
316 /// Renders the crate graph to GraphViz "dot" syntax.
317 pub fn view_crate_graph(&self, full: bool) -> Cancellable<Result<String, String>> {
318 self.with_db(|db| view_crate_graph::view_crate_graph(db, full))
321 pub fn expand_macro(&self, position: FilePosition) -> Cancellable<Option<ExpandedMacro>> {
322 self.with_db(|db| expand_macro::expand_macro(db, position))
325 /// Returns an edit to remove all newlines in the range, cleaning up minor
326 /// stuff like trailing commas.
327 pub fn join_lines(&self, config: &JoinLinesConfig, frange: FileRange) -> Cancellable<TextEdit> {
329 let parse = db.parse(frange.file_id);
330 join_lines::join_lines(config, &parse.tree(), frange.range)
334 /// Returns an edit which should be applied when opening a new line, fixing
335 /// up minor stuff like continuing the comment.
336 /// The edit will be a snippet (with `$0`).
337 pub fn on_enter(&self, position: FilePosition) -> Cancellable<Option<TextEdit>> {
338 self.with_db(|db| typing::on_enter(db, position))
341 /// Returns an edit which should be applied after a character was typed.
343 /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
345 pub fn on_char_typed(
347 position: FilePosition,
349 ) -> Cancellable<Option<SourceChange>> {
350 // Fast path to not even parse the file.
351 if !typing::TRIGGER_CHARS.contains(char_typed) {
354 self.with_db(|db| typing::on_char_typed(db, position, char_typed))
357 /// Returns a tree representation of symbols in the file. Useful to draw a
359 pub fn file_structure(&self, file_id: FileId) -> Cancellable<Vec<StructureNode>> {
360 self.with_db(|db| file_structure::file_structure(&db.parse(file_id).tree()))
363 /// Returns a list of the places in the file where type hints can be displayed.
366 config: &InlayHintsConfig,
368 ) -> Cancellable<Vec<InlayHint>> {
369 self.with_db(|db| inlay_hints::inlay_hints(db, file_id, config))
372 /// Returns the set of folding ranges.
373 pub fn folding_ranges(&self, file_id: FileId) -> Cancellable<Vec<Fold>> {
374 self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
377 /// Fuzzy searches for a symbol.
378 pub fn symbol_search(&self, query: Query) -> Cancellable<Vec<NavigationTarget>> {
380 symbol_index::world_symbols(db, query)
381 .into_iter() // xx: should we make this a par iter?
382 .filter_map(|s| s.try_to_nav(db))
387 /// Returns the definitions from the symbol at `position`.
388 pub fn goto_definition(
390 position: FilePosition,
391 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
392 self.with_db(|db| goto_definition::goto_definition(db, position))
395 /// Returns the declaration from the symbol at `position`.
396 pub fn goto_declaration(
398 position: FilePosition,
399 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
400 self.with_db(|db| goto_declaration::goto_declaration(db, position))
403 /// Returns the impls from the symbol at `position`.
404 pub fn goto_implementation(
406 position: FilePosition,
407 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
408 self.with_db(|db| goto_implementation::goto_implementation(db, position))
411 /// Returns the type definitions for the symbol at `position`.
412 pub fn goto_type_definition(
414 position: FilePosition,
415 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
416 self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
419 /// Finds all usages of the reference at point.
420 pub fn find_all_refs(
422 position: FilePosition,
423 search_scope: Option<SearchScope>,
424 ) -> Cancellable<Option<Vec<ReferenceSearchResult>>> {
425 self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, search_scope))
428 /// Finds all methods and free functions for the file. Does not return tests!
429 pub fn find_all_methods(&self, file_id: FileId) -> Cancellable<Vec<FileRange>> {
430 self.with_db(|db| fn_references::find_all_methods(db, file_id))
433 /// Returns a short text describing element at position.
436 config: &HoverConfig,
438 ) -> Cancellable<Option<RangeInfo<HoverResult>>> {
439 self.with_db(|db| hover::hover(db, range, config))
442 /// Returns moniker of symbol at position.
445 position: FilePosition,
446 ) -> Cancellable<Option<RangeInfo<Vec<moniker::MonikerResult>>>> {
447 self.with_db(|db| moniker::moniker(db, position))
450 /// Return URL(s) for the documentation of the symbol under the cursor.
451 pub fn external_docs(
453 position: FilePosition,
454 ) -> Cancellable<Option<doc_links::DocumentationLink>> {
455 self.with_db(|db| doc_links::external_docs(db, &position))
458 /// Computes parameter information for the given call expression.
459 pub fn call_info(&self, position: FilePosition) -> Cancellable<Option<CallInfo>> {
460 self.with_db(|db| call_info::call_info(db, position))
463 /// Computes call hierarchy candidates for the given file position.
464 pub fn call_hierarchy(
466 position: FilePosition,
467 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
468 self.with_db(|db| call_hierarchy::call_hierarchy(db, position))
471 /// Computes incoming calls for the given file position.
472 pub fn incoming_calls(&self, position: FilePosition) -> Cancellable<Option<Vec<CallItem>>> {
473 self.with_db(|db| call_hierarchy::incoming_calls(db, position))
476 /// Computes outgoing calls for the given file position.
477 pub fn outgoing_calls(&self, position: FilePosition) -> Cancellable<Option<Vec<CallItem>>> {
478 self.with_db(|db| call_hierarchy::outgoing_calls(db, position))
481 /// Returns a `mod name;` declaration which created the current module.
482 pub fn parent_module(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
483 self.with_db(|db| parent_module::parent_module(db, position))
486 /// Returns crates this file belongs too.
487 pub fn crate_for(&self, file_id: FileId) -> Cancellable<Vec<CrateId>> {
488 self.with_db(|db| parent_module::crate_for(db, file_id))
491 /// Returns the edition of the given crate.
492 pub fn crate_edition(&self, crate_id: CrateId) -> Cancellable<Edition> {
493 self.with_db(|db| db.crate_graph()[crate_id].edition)
496 /// Returns the root file of the given crate.
497 pub fn crate_root(&self, crate_id: CrateId) -> Cancellable<FileId> {
498 self.with_db(|db| db.crate_graph()[crate_id].root_file_id)
501 /// Returns the set of possible targets to run for the current file.
502 pub fn runnables(&self, file_id: FileId) -> Cancellable<Vec<Runnable>> {
503 self.with_db(|db| runnables::runnables(db, file_id))
506 /// Returns the set of tests for the given file position.
507 pub fn related_tests(
509 position: FilePosition,
510 search_scope: Option<SearchScope>,
511 ) -> Cancellable<Vec<Runnable>> {
512 self.with_db(|db| runnables::related_tests(db, position, search_scope))
515 /// Computes syntax highlighting for the given file
516 pub fn highlight(&self, file_id: FileId) -> Cancellable<Vec<HlRange>> {
517 self.with_db(|db| syntax_highlighting::highlight(db, file_id, None, false))
520 /// Computes all ranges to highlight for a given item in a file.
521 pub fn highlight_related(
523 config: HighlightRelatedConfig,
524 position: FilePosition,
525 ) -> Cancellable<Option<Vec<HighlightedRange>>> {
527 highlight_related::highlight_related(&Semantics::new(db), config, position)
531 /// Computes syntax highlighting for the given file range.
532 pub fn highlight_range(&self, frange: FileRange) -> Cancellable<Vec<HlRange>> {
534 syntax_highlighting::highlight(db, frange.file_id, Some(frange.range), false)
538 /// Computes syntax highlighting for the given file.
539 pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancellable<String> {
540 self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
543 /// Computes completions at the given position.
546 config: &CompletionConfig,
547 position: FilePosition,
548 ) -> Cancellable<Option<Vec<CompletionItem>>> {
549 self.with_db(|db| ide_completion::completions(db, config, position).map(Into::into))
552 /// Resolves additional completion data at the position given.
553 pub fn resolve_completion_edits(
555 config: &CompletionConfig,
556 position: FilePosition,
557 imports: impl IntoIterator<Item = (String, String)> + std::panic::UnwindSafe,
558 ) -> Cancellable<Vec<TextEdit>> {
560 .with_db(|db| ide_completion::resolve_completion_edits(db, config, position, imports))?
561 .unwrap_or_default())
564 /// Computes the set of diagnostics for the given file.
567 config: &DiagnosticsConfig,
568 resolve: AssistResolveStrategy,
570 ) -> Cancellable<Vec<Diagnostic>> {
571 self.with_db(|db| ide_diagnostics::diagnostics(db, config, &resolve, file_id))
574 /// Convenience function to return assists + quick fixes for diagnostics
575 pub fn assists_with_fixes(
577 assist_config: &AssistConfig,
578 diagnostics_config: &DiagnosticsConfig,
579 resolve: AssistResolveStrategy,
581 ) -> Cancellable<Vec<Assist>> {
582 let include_fixes = match &assist_config.allowed {
583 Some(it) => it.iter().any(|&it| it == AssistKind::None || it == AssistKind::QuickFix),
588 let diagnostic_assists = if include_fixes {
589 ide_diagnostics::diagnostics(db, diagnostics_config, &resolve, frange.file_id)
591 .flat_map(|it| it.fixes.unwrap_or_default())
592 .filter(|it| it.target.intersect(frange.range).is_some())
597 let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
598 let assists = ide_assists::assists(db, assist_config, resolve, frange);
600 let mut res = diagnostic_assists;
601 res.extend(ssr_assists.into_iter());
602 res.extend(assists.into_iter());
608 /// Returns the edit required to rename reference at the position to the new
612 position: FilePosition,
614 ) -> Cancellable<Result<SourceChange, RenameError>> {
615 self.with_db(|db| rename::rename(db, position, new_name))
618 pub fn prepare_rename(
620 position: FilePosition,
621 ) -> Cancellable<Result<RangeInfo<()>, RenameError>> {
622 self.with_db(|db| rename::prepare_rename(db, position))
625 pub fn will_rename_file(
629 ) -> Cancellable<Option<SourceChange>> {
630 self.with_db(|db| rename::will_rename_file(db, file_id, new_name_stem))
633 pub fn structural_search_replace(
637 resolve_context: FilePosition,
638 selections: Vec<FileRange>,
639 ) -> Cancellable<Result<SourceChange, SsrError>> {
641 let rule: ide_ssr::SsrRule = query.parse()?;
642 let mut match_finder =
643 ide_ssr::MatchFinder::in_context(db, resolve_context, selections);
644 match_finder.add_rule(rule)?;
645 let edits = if parse_only { Default::default() } else { match_finder.edits() };
646 Ok(SourceChange::from(edits))
652 config: &AnnotationConfig,
654 ) -> Cancellable<Vec<Annotation>> {
655 self.with_db(|db| annotations::annotations(db, config, file_id))
658 pub fn resolve_annotation(&self, annotation: Annotation) -> Cancellable<Annotation> {
659 self.with_db(|db| annotations::resolve_annotation(db, annotation))
665 direction: Direction,
666 ) -> Cancellable<Option<TextEdit>> {
667 self.with_db(|db| move_item::move_item(db, range, direction))
670 /// Performs an operation on the database that may be canceled.
672 /// rust-analyzer needs to be able to answer semantic questions about the
673 /// code while the code is being modified. A common problem is that a
674 /// long-running query is being calculated when a new change arrives.
676 /// We can't just apply the change immediately: this will cause the pending
677 /// query to see inconsistent state (it will observe an absence of
678 /// repeatable read). So what we do is we **cancel** all pending queries
679 /// before applying the change.
681 /// Salsa implements cancelation by unwinding with a special value and
682 /// catching it on the API boundary.
683 fn with_db<F, T>(&self, f: F) -> Cancellable<T>
685 F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
687 Cancelled::catch(|| f(&self.db))
692 fn analysis_is_send() {
693 fn is_send<T: Send>() {}
694 is_send::<Analysis>();