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,
413 ) -> Cancellable<Option<RangeInfo<HoverResult>>> {
414 self.with_db(|db| hover::hover(db, position, links_in_hover, documentation, markdown))
417 /// Return URL(s) for the documentation of the symbol under the cursor.
418 pub fn external_docs(
420 position: FilePosition,
421 ) -> Cancellable<Option<doc_links::DocumentationLink>> {
422 self.with_db(|db| doc_links::external_docs(db, &position))
425 /// Computes parameter information for the given call expression.
426 pub fn call_info(&self, position: FilePosition) -> Cancellable<Option<CallInfo>> {
427 self.with_db(|db| ide_db::call_info::call_info(db, position))
430 /// Computes call hierarchy candidates for the given file position.
431 pub fn call_hierarchy(
433 position: FilePosition,
434 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
435 self.with_db(|db| call_hierarchy::call_hierarchy(db, position))
438 /// Computes incoming calls for the given file position.
439 pub fn incoming_calls(&self, position: FilePosition) -> Cancellable<Option<Vec<CallItem>>> {
440 self.with_db(|db| call_hierarchy::incoming_calls(db, position))
443 /// Computes incoming calls for the given file position.
444 pub fn outgoing_calls(&self, position: FilePosition) -> Cancellable<Option<Vec<CallItem>>> {
445 self.with_db(|db| call_hierarchy::outgoing_calls(db, position))
448 /// Returns a `mod name;` declaration which created the current module.
449 pub fn parent_module(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
450 self.with_db(|db| parent_module::parent_module(db, position))
453 /// Returns crates this file belongs too.
454 pub fn crate_for(&self, file_id: FileId) -> Cancellable<Vec<CrateId>> {
455 self.with_db(|db| parent_module::crate_for(db, file_id))
458 /// Returns the edition of the given crate.
459 pub fn crate_edition(&self, crate_id: CrateId) -> Cancellable<Edition> {
460 self.with_db(|db| db.crate_graph()[crate_id].edition)
463 /// Returns the root file of the given crate.
464 pub fn crate_root(&self, crate_id: CrateId) -> Cancellable<FileId> {
465 self.with_db(|db| db.crate_graph()[crate_id].root_file_id)
468 /// Returns the set of possible targets to run for the current file.
469 pub fn runnables(&self, file_id: FileId) -> Cancellable<Vec<Runnable>> {
470 self.with_db(|db| runnables::runnables(db, file_id))
473 /// Returns the set of tests for the given file position.
474 pub fn related_tests(
476 position: FilePosition,
477 search_scope: Option<SearchScope>,
478 ) -> Cancellable<Vec<Runnable>> {
479 self.with_db(|db| runnables::related_tests(db, position, search_scope))
482 /// Computes syntax highlighting for the given file
483 pub fn highlight(&self, file_id: FileId) -> Cancellable<Vec<HlRange>> {
484 self.with_db(|db| syntax_highlighting::highlight(db, file_id, None, false))
487 /// Computes syntax highlighting for the given file range.
488 pub fn highlight_range(&self, frange: FileRange) -> Cancellable<Vec<HlRange>> {
490 syntax_highlighting::highlight(db, frange.file_id, Some(frange.range), false)
494 /// Computes syntax highlighting for the given file.
495 pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancellable<String> {
496 self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
499 /// Computes completions at the given position.
502 config: &CompletionConfig,
503 position: FilePosition,
504 ) -> Cancellable<Option<Vec<CompletionItem>>> {
505 self.with_db(|db| ide_completion::completions(db, config, position).map(Into::into))
508 /// Resolves additional completion data at the position given.
509 pub fn resolve_completion_edits(
511 config: &CompletionConfig,
512 position: FilePosition,
513 full_import_path: &str,
514 imported_name: String,
515 ) -> Cancellable<Vec<TextEdit>> {
518 ide_completion::resolve_completion_edits(
526 .unwrap_or_default())
529 /// Computes assists (aka code actions aka intentions) for the given
530 /// position. If `resolve == false`, computes enough info to show the
531 /// lightbulb list in the editor, but doesn't compute actual edits, to
532 /// improve performance.
535 config: &AssistConfig,
536 resolve: AssistResolveStrategy,
538 ) -> Cancellable<Vec<Assist>> {
540 let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
541 let mut acc = ide_assists::assists(db, config, resolve, frange);
542 acc.extend(ssr_assists.into_iter());
547 /// Computes the set of diagnostics for the given file.
550 config: &DiagnosticsConfig,
551 resolve: AssistResolveStrategy,
553 ) -> Cancellable<Vec<Diagnostic>> {
554 self.with_db(|db| ide_diagnostics::diagnostics(db, config, &resolve, file_id))
557 /// Convenience function to return assists + quick fixes for diagnostics
558 pub fn assists_with_fixes(
560 assist_config: &AssistConfig,
561 diagnostics_config: &DiagnosticsConfig,
562 resolve: AssistResolveStrategy,
564 ) -> Cancellable<Vec<Assist>> {
565 let include_fixes = match &assist_config.allowed {
566 Some(it) => it.iter().any(|&it| it == AssistKind::None || it == AssistKind::QuickFix),
571 let diagnostic_assists = if include_fixes {
572 ide_diagnostics::diagnostics(db, diagnostics_config, &resolve, frange.file_id)
574 .flat_map(|it| it.fixes.unwrap_or_default())
575 .filter(|it| it.target.intersect(frange.range).is_some())
580 let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
581 let assists = ide_assists::assists(db, assist_config, resolve, frange);
583 let mut res = diagnostic_assists;
584 res.extend(ssr_assists.into_iter());
585 res.extend(assists.into_iter());
591 /// Returns the edit required to rename reference at the position to the new
595 position: FilePosition,
597 ) -> Cancellable<Result<SourceChange, RenameError>> {
598 self.with_db(|db| rename::rename(db, position, new_name))
601 pub fn prepare_rename(
603 position: FilePosition,
604 ) -> Cancellable<Result<RangeInfo<()>, RenameError>> {
605 self.with_db(|db| rename::prepare_rename(db, position))
608 pub fn will_rename_file(
612 ) -> Cancellable<Option<SourceChange>> {
613 self.with_db(|db| rename::will_rename_file(db, file_id, new_name_stem))
616 pub fn structural_search_replace(
620 resolve_context: FilePosition,
621 selections: Vec<FileRange>,
622 ) -> Cancellable<Result<SourceChange, SsrError>> {
624 let rule: ide_ssr::SsrRule = query.parse()?;
625 let mut match_finder =
626 ide_ssr::MatchFinder::in_context(db, resolve_context, selections);
627 match_finder.add_rule(rule)?;
628 let edits = if parse_only { Default::default() } else { match_finder.edits() };
629 Ok(SourceChange::from(edits))
636 config: AnnotationConfig,
637 ) -> Cancellable<Vec<Annotation>> {
638 self.with_db(|db| annotations::annotations(db, file_id, config))
641 pub fn resolve_annotation(&self, annotation: Annotation) -> Cancellable<Annotation> {
642 self.with_db(|db| annotations::resolve_annotation(db, annotation))
648 direction: Direction,
649 ) -> Cancellable<Option<TextEdit>> {
650 self.with_db(|db| move_item::move_item(db, range, direction))
653 /// Performs an operation on the database that may be canceled.
655 /// rust-analyzer needs to be able to answer semantic questions about the
656 /// code while the code is being modified. A common problem is that a
657 /// long-running query is being calculated when a new change arrives.
659 /// We can't just apply the change immediately: this will cause the pending
660 /// query to see inconsistent state (it will observe an absence of
661 /// repeatable read). So what we do is we **cancel** all pending queries
662 /// before applying the change.
664 /// Salsa implements cancelation by unwinding with a special value and
665 /// catching it on the API boundary.
666 fn with_db<F, T>(&self, f: F) -> Cancellable<T>
668 F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
670 Cancelled::catch(|| f(&self.db))
675 fn analysis_is_send() {
676 fn is_send<T: Send>() {}
677 is_send::<Analysis>();