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)*) };
33 mod goto_implementation;
34 mod goto_type_definition;
47 mod syntax_highlighting;
59 use ide_db::base_db::{
60 salsa::{self, ParallelDatabase},
61 CheckCanceled, 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 diagnostics::{Diagnostic, DiagnosticsConfig, Severity},
75 display::navigation_target::NavigationTarget,
76 expand_macro::ExpandedMacro,
77 file_structure::{StructureNode, StructureNodeKind},
78 folding_ranges::{Fold, FoldKind},
79 hover::{HoverAction, HoverConfig, HoverGotoTypeData, HoverResult},
80 inlay_hints::{InlayHint, InlayHintsConfig, InlayKind},
83 prime_caches::PrimeCachesProgress,
84 references::{rename::RenameError, 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 Canceled, 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_ssr::SsrError;
113 pub use syntax::{TextRange, TextSize};
114 pub use text_edit::{Indel, TextEdit};
116 pub type Cancelable<T> = Result<T, Canceled>;
118 /// Info associated with a text range.
120 pub struct RangeInfo<T> {
121 pub range: TextRange,
125 impl<T> RangeInfo<T> {
126 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
127 RangeInfo { range, info }
131 /// `AnalysisHost` stores the current state of the world.
133 pub struct AnalysisHost {
138 pub fn new(lru_capacity: Option<usize>) -> AnalysisHost {
139 AnalysisHost { db: RootDatabase::new(lru_capacity) }
142 pub fn update_lru_capacity(&mut self, lru_capacity: Option<usize>) {
143 self.db.update_lru_capacity(lru_capacity);
146 /// Returns a snapshot of the current state, which you can query for
147 /// semantic information.
148 pub fn analysis(&self) -> Analysis {
149 Analysis { db: self.db.snapshot() }
152 /// Applies changes to the current state of the world. If there are
153 /// outstanding snapshots, they will be canceled.
154 pub fn apply_change(&mut self, change: Change) {
155 self.db.apply_change(change)
158 pub fn collect_garbage(&mut self) {
159 self.db.collect_garbage();
161 /// NB: this clears the database
162 pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes)> {
163 self.db.per_query_memory_usage()
165 pub fn request_cancellation(&mut self) {
166 self.db.request_cancellation();
168 pub fn raw_database(&self) -> &RootDatabase {
171 pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
176 impl Default for AnalysisHost {
177 fn default() -> AnalysisHost {
178 AnalysisHost::new(None)
182 /// Analysis is a snapshot of a world state at a moment in time. It is the main
183 /// entry point for asking semantic information about the world. When the world
184 /// state is advanced using `AnalysisHost::apply_change` method, all existing
185 /// `Analysis` are canceled (most method return `Err(Canceled)`).
187 pub struct Analysis {
188 db: salsa::Snapshot<RootDatabase>,
191 // As a general design guideline, `Analysis` API are intended to be independent
192 // from the language server protocol. That is, when exposing some functionality
193 // we should think in terms of "what API makes most sense" and not in terms of
194 // "what types LSP uses". Although currently LSP is the only consumer of the
195 // API, the API should in theory be usable as a library, or via a different
198 // Creates an analysis instance for a single file, without any extenal
199 // dependencies, stdlib support or ability to apply changes. See
200 // `AnalysisHost` for creating a fully-featured analysis.
201 pub fn from_single_file(text: String) -> (Analysis, FileId) {
202 let mut host = AnalysisHost::default();
203 let file_id = FileId(0);
204 let mut file_set = FileSet::default();
205 file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_string()));
206 let source_root = SourceRoot::new_local(file_set);
208 let mut change = Change::new();
209 change.set_roots(vec![source_root]);
210 let mut crate_graph = CrateGraph::default();
211 // FIXME: cfg options
212 // Default to enable test for single file.
213 let mut cfg_options = CfgOptions::default();
214 cfg_options.insert_atom("test".into());
215 crate_graph.add_crate_root(
217 Edition::Edition2018,
223 change.change_file(file_id, Some(Arc::new(text)));
224 change.set_crate_graph(crate_graph);
225 host.apply_change(change);
226 (host.analysis(), file_id)
229 /// Debug info about the current state of the analysis.
230 pub fn status(&self, file_id: Option<FileId>) -> Cancelable<String> {
231 self.with_db(|db| status::status(&*db, file_id))
234 pub fn prime_caches<F>(&self, cb: F) -> Cancelable<()>
236 F: Fn(PrimeCachesProgress) + Sync + std::panic::UnwindSafe,
238 self.with_db(move |db| prime_caches::prime_caches(db, &cb))
241 /// Gets the text of the source file.
242 pub fn file_text(&self, file_id: FileId) -> Cancelable<Arc<String>> {
243 self.with_db(|db| db.file_text(file_id))
246 /// Gets the syntax tree of the file.
247 pub fn parse(&self, file_id: FileId) -> Cancelable<SourceFile> {
248 self.with_db(|db| db.parse(file_id).tree())
251 /// Returns true if this file belongs to an immutable library.
252 pub fn is_library_file(&self, file_id: FileId) -> Cancelable<bool> {
253 use ide_db::base_db::SourceDatabaseExt;
254 self.with_db(|db| db.source_root(db.file_source_root(file_id)).is_library)
257 /// Gets the file's `LineIndex`: data structure to convert between absolute
258 /// offsets and line/column representation.
259 pub fn file_line_index(&self, file_id: FileId) -> Cancelable<Arc<LineIndex>> {
260 self.with_db(|db| db.line_index(file_id))
263 /// Selects the next syntactic nodes encompassing the range.
264 pub fn extend_selection(&self, frange: FileRange) -> Cancelable<TextRange> {
265 self.with_db(|db| extend_selection::extend_selection(db, frange))
268 /// Returns position of the matching brace (all types of braces are
270 pub fn matching_brace(&self, position: FilePosition) -> Cancelable<Option<TextSize>> {
272 let parse = db.parse(position.file_id);
273 let file = parse.tree();
274 matching_brace::matching_brace(&file, position.offset)
278 /// Returns a syntax tree represented as `String`, for debug purposes.
279 // FIXME: use a better name here.
283 text_range: Option<TextRange>,
284 ) -> Cancelable<String> {
285 self.with_db(|db| syntax_tree::syntax_tree(&db, file_id, text_range))
288 pub fn view_hir(&self, position: FilePosition) -> Cancelable<String> {
289 self.with_db(|db| view_hir::view_hir(&db, position))
292 pub fn view_item_tree(&self, file_id: FileId) -> Cancelable<String> {
293 self.with_db(|db| view_item_tree::view_item_tree(&db, file_id))
296 /// Renders the crate graph to GraphViz "dot" syntax.
297 pub fn view_crate_graph(&self) -> Cancelable<Result<String, String>> {
298 self.with_db(|db| view_crate_graph::view_crate_graph(&db))
301 pub fn expand_macro(&self, position: FilePosition) -> Cancelable<Option<ExpandedMacro>> {
302 self.with_db(|db| expand_macro::expand_macro(db, position))
305 /// Returns an edit to remove all newlines in the range, cleaning up minor
306 /// stuff like trailing commas.
307 pub fn join_lines(&self, frange: FileRange) -> Cancelable<TextEdit> {
309 let parse = db.parse(frange.file_id);
310 join_lines::join_lines(&parse.tree(), frange.range)
314 /// Returns an edit which should be applied when opening a new line, fixing
315 /// up minor stuff like continuing the comment.
316 /// The edit will be a snippet (with `$0`).
317 pub fn on_enter(&self, position: FilePosition) -> Cancelable<Option<TextEdit>> {
318 self.with_db(|db| typing::on_enter(&db, position))
321 /// Returns an edit which should be applied after a character was typed.
323 /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
325 pub fn on_char_typed(
327 position: FilePosition,
329 ) -> Cancelable<Option<SourceChange>> {
330 // Fast path to not even parse the file.
331 if !typing::TRIGGER_CHARS.contains(char_typed) {
334 self.with_db(|db| typing::on_char_typed(&db, position, char_typed))
337 /// Returns a tree representation of symbols in the file. Useful to draw a
339 pub fn file_structure(&self, file_id: FileId) -> Cancelable<Vec<StructureNode>> {
340 self.with_db(|db| file_structure::file_structure(&db.parse(file_id).tree()))
343 /// Returns a list of the places in the file where type hints can be displayed.
347 config: &InlayHintsConfig,
348 ) -> Cancelable<Vec<InlayHint>> {
349 self.with_db(|db| inlay_hints::inlay_hints(db, file_id, config))
352 /// Returns the set of folding ranges.
353 pub fn folding_ranges(&self, file_id: FileId) -> Cancelable<Vec<Fold>> {
354 self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
357 /// Fuzzy searches for a symbol.
358 pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
360 symbol_index::world_symbols(db, query)
362 .map(|s| s.to_nav(db))
367 /// Returns the definitions from the symbol at `position`.
368 pub fn goto_definition(
370 position: FilePosition,
371 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
372 self.with_db(|db| goto_definition::goto_definition(db, position))
375 /// Returns the impls from the symbol at `position`.
376 pub fn goto_implementation(
378 position: FilePosition,
379 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
380 self.with_db(|db| goto_implementation::goto_implementation(db, position))
383 /// Returns the type definitions for the symbol at `position`.
384 pub fn goto_type_definition(
386 position: FilePosition,
387 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
388 self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
391 /// Finds all usages of the reference at point.
392 pub fn find_all_refs(
394 position: FilePosition,
395 search_scope: Option<SearchScope>,
396 ) -> Cancelable<Option<ReferenceSearchResult>> {
397 self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, search_scope))
400 /// Finds all methods and free functions for the file. Does not return tests!
401 pub fn find_all_methods(&self, file_id: FileId) -> Cancelable<Vec<FileRange>> {
402 self.with_db(|db| fn_references::find_all_methods(db, file_id))
405 /// Returns a short text describing element at position.
408 position: FilePosition,
409 links_in_hover: bool,
411 ) -> Cancelable<Option<RangeInfo<HoverResult>>> {
412 self.with_db(|db| hover::hover(db, position, links_in_hover, markdown))
415 /// Return URL(s) for the documentation of the symbol under the cursor.
416 pub fn external_docs(
418 position: FilePosition,
419 ) -> Cancelable<Option<doc_links::DocumentationLink>> {
420 self.with_db(|db| doc_links::external_docs(db, &position))
423 /// Computes parameter information for the given call expression.
424 pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
425 self.with_db(|db| ide_db::call_info::call_info(db, position))
428 /// Computes call hierarchy candidates for the given file position.
429 pub fn call_hierarchy(
431 position: FilePosition,
432 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
433 self.with_db(|db| call_hierarchy::call_hierarchy(db, position))
436 /// Computes incoming calls for the given file position.
437 pub fn incoming_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
438 self.with_db(|db| call_hierarchy::incoming_calls(db, position))
441 /// Computes incoming calls for the given file position.
442 pub fn outgoing_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
443 self.with_db(|db| call_hierarchy::outgoing_calls(db, position))
446 /// Returns a `mod name;` declaration which created the current module.
447 pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
448 self.with_db(|db| parent_module::parent_module(db, position))
451 /// Returns crates this file belongs too.
452 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
453 self.with_db(|db| parent_module::crate_for(db, file_id))
456 /// Returns the edition of the given crate.
457 pub fn crate_edition(&self, crate_id: CrateId) -> Cancelable<Edition> {
458 self.with_db(|db| db.crate_graph()[crate_id].edition)
461 /// Returns the root file of the given crate.
462 pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
463 self.with_db(|db| db.crate_graph()[crate_id].root_file_id)
466 /// Returns the set of possible targets to run for the current file.
467 pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
468 self.with_db(|db| runnables::runnables(db, file_id))
471 /// Returns the set of tests for the given file position.
472 pub fn related_tests(
474 position: FilePosition,
475 search_scope: Option<SearchScope>,
476 ) -> Cancelable<Vec<Runnable>> {
477 self.with_db(|db| runnables::related_tests(db, position, search_scope))
480 /// Computes syntax highlighting for the given file
481 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HlRange>> {
482 self.with_db(|db| syntax_highlighting::highlight(db, file_id, None, false))
485 /// Computes syntax highlighting for the given file range.
486 pub fn highlight_range(&self, frange: FileRange) -> Cancelable<Vec<HlRange>> {
488 syntax_highlighting::highlight(db, frange.file_id, Some(frange.range), false)
492 /// Computes syntax highlighting for the given file.
493 pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancelable<String> {
494 self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
497 /// Computes completions at the given position.
500 config: &CompletionConfig,
501 position: FilePosition,
502 ) -> Cancelable<Option<Vec<CompletionItem>>> {
503 self.with_db(|db| ide_completion::completions(db, config, position).map(Into::into))
506 /// Resolves additional completion data at the position given.
507 pub fn resolve_completion_edits(
509 config: &CompletionConfig,
510 position: FilePosition,
511 full_import_path: &str,
512 imported_name: String,
513 ) -> Cancelable<Vec<TextEdit>> {
516 ide_completion::resolve_completion_edits(
524 .unwrap_or_default())
527 /// Computes assists (aka code actions aka intentions) for the given
528 /// position. If `resolve == false`, computes enough info to show the
529 /// lightbulb list in the editor, but doesn't compute actual edits, to
530 /// improve performance.
533 config: &AssistConfig,
534 resolve: AssistResolveStrategy,
536 ) -> Cancelable<Vec<Assist>> {
538 let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
539 let mut acc = Assist::get(db, config, resolve, frange);
540 acc.extend(ssr_assists.into_iter());
545 /// Computes the set of diagnostics for the given file.
548 config: &DiagnosticsConfig,
549 resolve: AssistResolveStrategy,
551 ) -> Cancelable<Vec<Diagnostic>> {
552 self.with_db(|db| diagnostics::diagnostics(db, config, &resolve, file_id))
555 /// Convenience function to return assists + quick fixes for diagnostics
556 pub fn assists_with_fixes(
558 assist_config: &AssistConfig,
559 diagnostics_config: &DiagnosticsConfig,
560 resolve: AssistResolveStrategy,
562 ) -> Cancelable<Vec<Assist>> {
563 let include_fixes = match &assist_config.allowed {
564 Some(it) => it.iter().any(|&it| it == AssistKind::None || it == AssistKind::QuickFix),
569 let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
570 let diagnostic_assists = if include_fixes {
571 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())
580 let mut res = Assist::get(db, assist_config, resolve, frange);
581 res.extend(ssr_assists.into_iter());
582 res.extend(diagnostic_assists.into_iter());
588 /// Returns the edit required to rename reference at the position to the new
592 position: FilePosition,
594 ) -> Cancelable<Result<SourceChange, RenameError>> {
595 self.with_db(|db| references::rename::rename(db, position, new_name))
598 pub fn prepare_rename(
600 position: FilePosition,
601 ) -> Cancelable<Result<RangeInfo<()>, RenameError>> {
602 self.with_db(|db| references::rename::prepare_rename(db, position))
605 pub fn will_rename_file(
609 ) -> Cancelable<Option<SourceChange>> {
610 self.with_db(|db| references::rename::will_rename_file(db, file_id, new_name_stem))
613 pub fn structural_search_replace(
617 resolve_context: FilePosition,
618 selections: Vec<FileRange>,
619 ) -> Cancelable<Result<SourceChange, SsrError>> {
621 let rule: ide_ssr::SsrRule = query.parse()?;
622 let mut match_finder =
623 ide_ssr::MatchFinder::in_context(db, resolve_context, selections);
624 match_finder.add_rule(rule)?;
625 let edits = if parse_only { Default::default() } else { match_finder.edits() };
626 Ok(SourceChange::from(edits))
633 config: AnnotationConfig,
634 ) -> Cancelable<Vec<Annotation>> {
635 self.with_db(|db| annotations::annotations(db, file_id, config))
638 pub fn resolve_annotation(&self, annotation: Annotation) -> Cancelable<Annotation> {
639 self.with_db(|db| annotations::resolve_annotation(db, annotation))
645 direction: Direction,
646 ) -> Cancelable<Option<TextEdit>> {
647 self.with_db(|db| move_item::move_item(db, range, direction))
650 /// Performs an operation on that may be Canceled.
651 fn with_db<F, T>(&self, f: F) -> Cancelable<T>
653 F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
655 self.db.catch_canceled(f)
660 fn analysis_is_send() {
661 fn is_send<T: Send>() {}
662 is_send::<Analysis>();