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,
224 change.change_file(file_id, Some(Arc::new(text)));
225 change.set_crate_graph(crate_graph);
226 host.apply_change(change);
227 (host.analysis(), file_id)
230 /// Debug info about the current state of the analysis.
231 pub fn status(&self, file_id: Option<FileId>) -> Cancellable<String> {
232 self.with_db(|db| status::status(&*db, file_id))
235 pub fn prime_caches<F>(&self, cb: F) -> Cancellable<()>
237 F: Fn(PrimeCachesProgress) + Sync + std::panic::UnwindSafe,
239 self.with_db(move |db| prime_caches::prime_caches(db, &cb))
242 /// Gets the text of the source file.
243 pub fn file_text(&self, file_id: FileId) -> Cancellable<Arc<String>> {
244 self.with_db(|db| db.file_text(file_id))
247 /// Gets the syntax tree of the file.
248 pub fn parse(&self, file_id: FileId) -> Cancellable<SourceFile> {
249 self.with_db(|db| db.parse(file_id).tree())
252 /// Returns true if this file belongs to an immutable library.
253 pub fn is_library_file(&self, file_id: FileId) -> Cancellable<bool> {
254 use ide_db::base_db::SourceDatabaseExt;
255 self.with_db(|db| db.source_root(db.file_source_root(file_id)).is_library)
258 /// Gets the file's `LineIndex`: data structure to convert between absolute
259 /// offsets and line/column representation.
260 pub fn file_line_index(&self, file_id: FileId) -> Cancellable<Arc<LineIndex>> {
261 self.with_db(|db| db.line_index(file_id))
264 /// Selects the next syntactic nodes encompassing the range.
265 pub fn extend_selection(&self, frange: FileRange) -> Cancellable<TextRange> {
266 self.with_db(|db| extend_selection::extend_selection(db, frange))
269 /// Returns position of the matching brace (all types of braces are
271 pub fn matching_brace(&self, position: FilePosition) -> Cancellable<Option<TextSize>> {
273 let parse = db.parse(position.file_id);
274 let file = parse.tree();
275 matching_brace::matching_brace(&file, position.offset)
279 /// Returns a syntax tree represented as `String`, for debug purposes.
280 // FIXME: use a better name here.
284 text_range: Option<TextRange>,
285 ) -> Cancellable<String> {
286 self.with_db(|db| syntax_tree::syntax_tree(db, file_id, text_range))
289 pub fn view_hir(&self, position: FilePosition) -> Cancellable<String> {
290 self.with_db(|db| view_hir::view_hir(db, position))
293 pub fn view_item_tree(&self, file_id: FileId) -> Cancellable<String> {
294 self.with_db(|db| view_item_tree::view_item_tree(db, file_id))
297 /// Renders the crate graph to GraphViz "dot" syntax.
298 pub fn view_crate_graph(&self) -> Cancellable<Result<String, String>> {
299 self.with_db(|db| view_crate_graph::view_crate_graph(db))
302 pub fn expand_macro(&self, position: FilePosition) -> Cancellable<Option<ExpandedMacro>> {
303 self.with_db(|db| expand_macro::expand_macro(db, position))
306 /// Returns an edit to remove all newlines in the range, cleaning up minor
307 /// stuff like trailing commas.
308 pub fn join_lines(&self, frange: FileRange) -> Cancellable<TextEdit> {
310 let parse = db.parse(frange.file_id);
311 join_lines::join_lines(&parse.tree(), frange.range)
315 /// Returns an edit which should be applied when opening a new line, fixing
316 /// up minor stuff like continuing the comment.
317 /// The edit will be a snippet (with `$0`).
318 pub fn on_enter(&self, position: FilePosition) -> Cancellable<Option<TextEdit>> {
319 self.with_db(|db| typing::on_enter(db, position))
322 /// Returns an edit which should be applied after a character was typed.
324 /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
326 pub fn on_char_typed(
328 position: FilePosition,
330 ) -> Cancellable<Option<SourceChange>> {
331 // Fast path to not even parse the file.
332 if !typing::TRIGGER_CHARS.contains(char_typed) {
335 self.with_db(|db| typing::on_char_typed(db, position, char_typed))
338 /// Returns a tree representation of symbols in the file. Useful to draw a
340 pub fn file_structure(&self, file_id: FileId) -> Cancellable<Vec<StructureNode>> {
341 self.with_db(|db| file_structure::file_structure(&db.parse(file_id).tree()))
344 /// Returns a list of the places in the file where type hints can be displayed.
348 config: &InlayHintsConfig,
349 ) -> Cancellable<Vec<InlayHint>> {
350 self.with_db(|db| inlay_hints::inlay_hints(db, file_id, config))
353 /// Returns the set of folding ranges.
354 pub fn folding_ranges(&self, file_id: FileId) -> Cancellable<Vec<Fold>> {
355 self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
358 /// Fuzzy searches for a symbol.
359 pub fn symbol_search(&self, query: Query) -> Cancellable<Vec<NavigationTarget>> {
361 symbol_index::world_symbols(db, query)
363 .map(|s| s.to_nav(db))
368 /// Returns the definitions from the symbol at `position`.
369 pub fn goto_definition(
371 position: FilePosition,
372 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
373 self.with_db(|db| goto_definition::goto_definition(db, position))
376 /// Returns the impls from the symbol at `position`.
377 pub fn goto_implementation(
379 position: FilePosition,
380 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
381 self.with_db(|db| goto_implementation::goto_implementation(db, position))
384 /// Returns the type definitions for the symbol at `position`.
385 pub fn goto_type_definition(
387 position: FilePosition,
388 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
389 self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
392 /// Finds all usages of the reference at point.
393 pub fn find_all_refs(
395 position: FilePosition,
396 search_scope: Option<SearchScope>,
397 ) -> Cancellable<Option<ReferenceSearchResult>> {
398 self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, search_scope))
401 /// Finds all methods and free functions for the file. Does not return tests!
402 pub fn find_all_methods(&self, file_id: FileId) -> Cancellable<Vec<FileRange>> {
403 self.with_db(|db| fn_references::find_all_methods(db, file_id))
406 /// Returns a short text describing element at position.
409 position: FilePosition,
410 links_in_hover: bool,
412 ) -> Cancellable<Option<RangeInfo<HoverResult>>> {
413 self.with_db(|db| hover::hover(db, position, links_in_hover, markdown))
416 /// Return URL(s) for the documentation of the symbol under the cursor.
417 pub fn external_docs(
419 position: FilePosition,
420 ) -> Cancellable<Option<doc_links::DocumentationLink>> {
421 self.with_db(|db| doc_links::external_docs(db, &position))
424 /// Computes parameter information for the given call expression.
425 pub fn call_info(&self, position: FilePosition) -> Cancellable<Option<CallInfo>> {
426 self.with_db(|db| ide_db::call_info::call_info(db, position))
429 /// Computes call hierarchy candidates for the given file position.
430 pub fn call_hierarchy(
432 position: FilePosition,
433 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
434 self.with_db(|db| call_hierarchy::call_hierarchy(db, position))
437 /// Computes incoming calls for the given file position.
438 pub fn incoming_calls(&self, position: FilePosition) -> Cancellable<Option<Vec<CallItem>>> {
439 self.with_db(|db| call_hierarchy::incoming_calls(db, position))
442 /// Computes incoming calls for the given file position.
443 pub fn outgoing_calls(&self, position: FilePosition) -> Cancellable<Option<Vec<CallItem>>> {
444 self.with_db(|db| call_hierarchy::outgoing_calls(db, position))
447 /// Returns a `mod name;` declaration which created the current module.
448 pub fn parent_module(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
449 self.with_db(|db| parent_module::parent_module(db, position))
452 /// Returns crates this file belongs too.
453 pub fn crate_for(&self, file_id: FileId) -> Cancellable<Vec<CrateId>> {
454 self.with_db(|db| parent_module::crate_for(db, file_id))
457 /// Returns the edition of the given crate.
458 pub fn crate_edition(&self, crate_id: CrateId) -> Cancellable<Edition> {
459 self.with_db(|db| db.crate_graph()[crate_id].edition)
462 /// Returns the root file of the given crate.
463 pub fn crate_root(&self, crate_id: CrateId) -> Cancellable<FileId> {
464 self.with_db(|db| db.crate_graph()[crate_id].root_file_id)
467 /// Returns the set of possible targets to run for the current file.
468 pub fn runnables(&self, file_id: FileId) -> Cancellable<Vec<Runnable>> {
469 self.with_db(|db| runnables::runnables(db, file_id))
472 /// Returns the set of tests for the given file position.
473 pub fn related_tests(
475 position: FilePosition,
476 search_scope: Option<SearchScope>,
477 ) -> Cancellable<Vec<Runnable>> {
478 self.with_db(|db| runnables::related_tests(db, position, search_scope))
481 /// Computes syntax highlighting for the given file
482 pub fn highlight(&self, file_id: FileId) -> Cancellable<Vec<HlRange>> {
483 self.with_db(|db| syntax_highlighting::highlight(db, file_id, None, false))
486 /// Computes syntax highlighting for the given file range.
487 pub fn highlight_range(&self, frange: FileRange) -> Cancellable<Vec<HlRange>> {
489 syntax_highlighting::highlight(db, frange.file_id, Some(frange.range), false)
493 /// Computes syntax highlighting for the given file.
494 pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancellable<String> {
495 self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
498 /// Computes completions at the given position.
501 config: &CompletionConfig,
502 position: FilePosition,
503 ) -> Cancellable<Option<Vec<CompletionItem>>> {
504 self.with_db(|db| ide_completion::completions(db, config, position).map(Into::into))
507 /// Resolves additional completion data at the position given.
508 pub fn resolve_completion_edits(
510 config: &CompletionConfig,
511 position: FilePosition,
512 full_import_path: &str,
513 imported_name: String,
514 ) -> Cancellable<Vec<TextEdit>> {
517 ide_completion::resolve_completion_edits(
525 .unwrap_or_default())
528 /// Computes assists (aka code actions aka intentions) for the given
529 /// position. If `resolve == false`, computes enough info to show the
530 /// lightbulb list in the editor, but doesn't compute actual edits, to
531 /// improve performance.
534 config: &AssistConfig,
535 resolve: AssistResolveStrategy,
537 ) -> Cancellable<Vec<Assist>> {
539 let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
540 let mut acc = ide_assists::assists(db, config, resolve, frange);
541 acc.extend(ssr_assists.into_iter());
546 /// Computes the set of diagnostics for the given file.
549 config: &DiagnosticsConfig,
550 resolve: AssistResolveStrategy,
552 ) -> Cancellable<Vec<Diagnostic>> {
553 self.with_db(|db| ide_diagnostics::diagnostics(db, config, &resolve, file_id))
556 /// Convenience function to return assists + quick fixes for diagnostics
557 pub fn assists_with_fixes(
559 assist_config: &AssistConfig,
560 diagnostics_config: &DiagnosticsConfig,
561 resolve: AssistResolveStrategy,
563 ) -> Cancellable<Vec<Assist>> {
564 let include_fixes = match &assist_config.allowed {
565 Some(it) => it.iter().any(|&it| it == AssistKind::None || it == AssistKind::QuickFix),
570 let diagnostic_assists = if include_fixes {
571 ide_diagnostics::diagnostics(db, diagnostics_config, &resolve, frange.file_id)
573 .flat_map(|it| it.fixes.unwrap_or_default())
574 .filter(|it| it.target.intersect(frange.range).is_some())
579 let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
580 let assists = ide_assists::assists(db, assist_config, resolve, frange);
582 let mut res = diagnostic_assists;
583 res.extend(ssr_assists.into_iter());
584 res.extend(assists.into_iter());
590 /// Returns the edit required to rename reference at the position to the new
594 position: FilePosition,
596 ) -> Cancellable<Result<SourceChange, RenameError>> {
597 self.with_db(|db| rename::rename(db, position, new_name))
600 pub fn prepare_rename(
602 position: FilePosition,
603 ) -> Cancellable<Result<RangeInfo<()>, RenameError>> {
604 self.with_db(|db| rename::prepare_rename(db, position))
607 pub fn will_rename_file(
611 ) -> Cancellable<Option<SourceChange>> {
612 self.with_db(|db| rename::will_rename_file(db, file_id, new_name_stem))
615 pub fn structural_search_replace(
619 resolve_context: FilePosition,
620 selections: Vec<FileRange>,
621 ) -> Cancellable<Result<SourceChange, SsrError>> {
623 let rule: ide_ssr::SsrRule = query.parse()?;
624 let mut match_finder =
625 ide_ssr::MatchFinder::in_context(db, resolve_context, selections);
626 match_finder.add_rule(rule)?;
627 let edits = if parse_only { Default::default() } else { match_finder.edits() };
628 Ok(SourceChange::from(edits))
635 config: AnnotationConfig,
636 ) -> Cancellable<Vec<Annotation>> {
637 self.with_db(|db| annotations::annotations(db, file_id, config))
640 pub fn resolve_annotation(&self, annotation: Annotation) -> Cancellable<Annotation> {
641 self.with_db(|db| annotations::resolve_annotation(db, annotation))
647 direction: Direction,
648 ) -> Cancellable<Option<TextEdit>> {
649 self.with_db(|db| move_item::move_item(db, range, direction))
652 /// Performs an operation on the database that may be canceled.
654 /// rust-analyzer needs to be able to answer semantic questions about the
655 /// code while the code is being modified. A common problem is that a
656 /// long-running query is being calculated when a new change arrives.
658 /// We can't just apply the change immediately: this will cause the pending
659 /// query to see inconsistent state (it will observe an absence of
660 /// repeatable read). So what we do is we **cancel** all pending queries
661 /// before applying the change.
663 /// Salsa implements cancelation by unwinding with a special value and
664 /// catching it on the API boundary.
665 fn with_db<F, T>(&self, f: F) -> Cancellable<T>
667 F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
669 Cancelled::catch(|| f(&self.db))
674 fn analysis_is_send() {
675 fn is_send<T: Send>() {}
676 is_send::<Analysis>();