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;
58 use ide_db::base_db::{
59 salsa::{self, ParallelDatabase},
60 CheckCanceled, Env, FileLoader, FileSet, SourceDatabase, VfsPath,
63 symbol_index::{self, FileSymbol},
66 use syntax::SourceFile;
68 use crate::display::ToNav;
71 annotations::{Annotation, AnnotationConfig, AnnotationKind},
72 call_hierarchy::CallItem,
73 diagnostics::{Diagnostic, DiagnosticsConfig, Severity},
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::{rename::RenameError, ReferenceSearchResult},
84 runnables::{Runnable, RunnableKind, TestId},
85 syntax_highlighting::{
86 tags::{Highlight, HlMod, HlMods, HlOperator, HlPunct, HlTag},
90 pub use hir::{Documentation, Semantics};
91 pub use ide_assists::{
92 Assist, AssistConfig, AssistId, AssistKind, AssistResolveStrategy, SingleResolve,
94 pub use ide_completion::{
95 CompletionConfig, CompletionItem, CompletionItemKind, CompletionRelevance, ImportEdit,
100 Canceled, Change, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange,
101 SourceRoot, SourceRootId,
105 line_index::{LineCol, LineColUtf16, LineIndex},
106 search::{ReferenceAccess, SearchScope},
107 source_change::{FileSystemEdit, SourceChange},
109 RootDatabase, SymbolKind,
111 pub use ide_ssr::SsrError;
112 pub use syntax::{TextRange, TextSize};
113 pub use text_edit::{Indel, TextEdit};
115 pub type Cancelable<T> = Result<T, Canceled>;
117 /// Info associated with a text range.
119 pub struct RangeInfo<T> {
120 pub range: TextRange,
124 impl<T> RangeInfo<T> {
125 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
126 RangeInfo { range, info }
130 /// `AnalysisHost` stores the current state of the world.
132 pub struct AnalysisHost {
137 pub fn new(lru_capacity: Option<usize>) -> AnalysisHost {
138 AnalysisHost { db: RootDatabase::new(lru_capacity) }
141 pub fn update_lru_capacity(&mut self, lru_capacity: Option<usize>) {
142 self.db.update_lru_capacity(lru_capacity);
145 /// Returns a snapshot of the current state, which you can query for
146 /// semantic information.
147 pub fn analysis(&self) -> Analysis {
148 Analysis { db: self.db.snapshot() }
151 /// Applies changes to the current state of the world. If there are
152 /// outstanding snapshots, they will be canceled.
153 pub fn apply_change(&mut self, change: Change) {
154 self.db.apply_change(change)
157 pub fn collect_garbage(&mut self) {
158 self.db.collect_garbage();
160 /// NB: this clears the database
161 pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes)> {
162 self.db.per_query_memory_usage()
164 pub fn request_cancellation(&mut self) {
165 self.db.request_cancellation();
167 pub fn raw_database(&self) -> &RootDatabase {
170 pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
175 impl Default for AnalysisHost {
176 fn default() -> AnalysisHost {
177 AnalysisHost::new(None)
181 /// Analysis is a snapshot of a world state at a moment in time. It is the main
182 /// entry point for asking semantic information about the world. When the world
183 /// state is advanced using `AnalysisHost::apply_change` method, all existing
184 /// `Analysis` are canceled (most method return `Err(Canceled)`).
186 pub struct Analysis {
187 db: salsa::Snapshot<RootDatabase>,
190 // As a general design guideline, `Analysis` API are intended to be independent
191 // from the language server protocol. That is, when exposing some functionality
192 // we should think in terms of "what API makes most sense" and not in terms of
193 // "what types LSP uses". Although currently LSP is the only consumer of the
194 // API, the API should in theory be usable as a library, or via a different
197 // Creates an analysis instance for a single file, without any extenal
198 // dependencies, stdlib support or ability to apply changes. See
199 // `AnalysisHost` for creating a fully-featured analysis.
200 pub fn from_single_file(text: String) -> (Analysis, FileId) {
201 let mut host = AnalysisHost::default();
202 let file_id = FileId(0);
203 let mut file_set = FileSet::default();
204 file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_string()));
205 let source_root = SourceRoot::new_local(file_set);
207 let mut change = Change::new();
208 change.set_roots(vec![source_root]);
209 let mut crate_graph = CrateGraph::default();
210 // FIXME: cfg options
211 // Default to enable test for single file.
212 let mut cfg_options = CfgOptions::default();
213 cfg_options.insert_atom("test".into());
214 crate_graph.add_crate_root(
216 Edition::Edition2018,
222 change.change_file(file_id, Some(Arc::new(text)));
223 change.set_crate_graph(crate_graph);
224 host.apply_change(change);
225 (host.analysis(), file_id)
228 /// Debug info about the current state of the analysis.
229 pub fn status(&self, file_id: Option<FileId>) -> Cancelable<String> {
230 self.with_db(|db| status::status(&*db, file_id))
233 pub fn prime_caches<F>(&self, cb: F) -> Cancelable<()>
235 F: Fn(PrimeCachesProgress) + Sync + std::panic::UnwindSafe,
237 self.with_db(move |db| prime_caches::prime_caches(db, &cb))
240 /// Gets the text of the source file.
241 pub fn file_text(&self, file_id: FileId) -> Cancelable<Arc<String>> {
242 self.with_db(|db| db.file_text(file_id))
245 /// Gets the syntax tree of the file.
246 pub fn parse(&self, file_id: FileId) -> Cancelable<SourceFile> {
247 self.with_db(|db| db.parse(file_id).tree())
250 /// Returns true if this file belongs to an immutable library.
251 pub fn is_library_file(&self, file_id: FileId) -> Cancelable<bool> {
252 use ide_db::base_db::SourceDatabaseExt;
253 self.with_db(|db| db.source_root(db.file_source_root(file_id)).is_library)
256 /// Gets the file's `LineIndex`: data structure to convert between absolute
257 /// offsets and line/column representation.
258 pub fn file_line_index(&self, file_id: FileId) -> Cancelable<Arc<LineIndex>> {
259 self.with_db(|db| db.line_index(file_id))
262 /// Selects the next syntactic nodes encompassing the range.
263 pub fn extend_selection(&self, frange: FileRange) -> Cancelable<TextRange> {
264 self.with_db(|db| extend_selection::extend_selection(db, frange))
267 /// Returns position of the matching brace (all types of braces are
269 pub fn matching_brace(&self, position: FilePosition) -> Cancelable<Option<TextSize>> {
271 let parse = db.parse(position.file_id);
272 let file = parse.tree();
273 matching_brace::matching_brace(&file, position.offset)
277 /// Returns a syntax tree represented as `String`, for debug purposes.
278 // FIXME: use a better name here.
282 text_range: Option<TextRange>,
283 ) -> Cancelable<String> {
284 self.with_db(|db| syntax_tree::syntax_tree(&db, file_id, text_range))
287 pub fn view_hir(&self, position: FilePosition) -> Cancelable<String> {
288 self.with_db(|db| view_hir::view_hir(&db, position))
291 /// Renders the crate graph to GraphViz "dot" syntax.
292 pub fn view_crate_graph(&self) -> Cancelable<Result<String, String>> {
293 self.with_db(|db| view_crate_graph::view_crate_graph(&db))
296 pub fn expand_macro(&self, position: FilePosition) -> Cancelable<Option<ExpandedMacro>> {
297 self.with_db(|db| expand_macro::expand_macro(db, position))
300 /// Returns an edit to remove all newlines in the range, cleaning up minor
301 /// stuff like trailing commas.
302 pub fn join_lines(&self, frange: FileRange) -> Cancelable<TextEdit> {
304 let parse = db.parse(frange.file_id);
305 join_lines::join_lines(&parse.tree(), frange.range)
309 /// Returns an edit which should be applied when opening a new line, fixing
310 /// up minor stuff like continuing the comment.
311 /// The edit will be a snippet (with `$0`).
312 pub fn on_enter(&self, position: FilePosition) -> Cancelable<Option<TextEdit>> {
313 self.with_db(|db| typing::on_enter(&db, position))
316 /// Returns an edit which should be applied after a character was typed.
318 /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
320 pub fn on_char_typed(
322 position: FilePosition,
324 ) -> Cancelable<Option<SourceChange>> {
325 // Fast path to not even parse the file.
326 if !typing::TRIGGER_CHARS.contains(char_typed) {
329 self.with_db(|db| typing::on_char_typed(&db, position, char_typed))
332 /// Returns a tree representation of symbols in the file. Useful to draw a
334 pub fn file_structure(&self, file_id: FileId) -> Cancelable<Vec<StructureNode>> {
335 self.with_db(|db| file_structure::file_structure(&db.parse(file_id).tree()))
338 /// Returns a list of the places in the file where type hints can be displayed.
342 config: &InlayHintsConfig,
343 ) -> Cancelable<Vec<InlayHint>> {
344 self.with_db(|db| inlay_hints::inlay_hints(db, file_id, config))
347 /// Returns the set of folding ranges.
348 pub fn folding_ranges(&self, file_id: FileId) -> Cancelable<Vec<Fold>> {
349 self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
352 /// Fuzzy searches for a symbol.
353 pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
355 symbol_index::world_symbols(db, query)
357 .map(|s| s.to_nav(db))
362 /// Returns the definitions from the symbol at `position`.
363 pub fn goto_definition(
365 position: FilePosition,
366 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
367 self.with_db(|db| goto_definition::goto_definition(db, position))
370 /// Returns the impls from the symbol at `position`.
371 pub fn goto_implementation(
373 position: FilePosition,
374 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
375 self.with_db(|db| goto_implementation::goto_implementation(db, position))
378 /// Returns the type definitions for the symbol at `position`.
379 pub fn goto_type_definition(
381 position: FilePosition,
382 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
383 self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
386 /// Finds all usages of the reference at point.
387 pub fn find_all_refs(
389 position: FilePosition,
390 search_scope: Option<SearchScope>,
391 ) -> Cancelable<Option<ReferenceSearchResult>> {
392 self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, search_scope))
395 /// Finds all methods and free functions for the file. Does not return tests!
396 pub fn find_all_methods(&self, file_id: FileId) -> Cancelable<Vec<FileRange>> {
397 self.with_db(|db| fn_references::find_all_methods(db, file_id))
400 /// Returns a short text describing element at position.
403 position: FilePosition,
404 links_in_hover: bool,
406 ) -> Cancelable<Option<RangeInfo<HoverResult>>> {
407 self.with_db(|db| hover::hover(db, position, links_in_hover, markdown))
410 /// Return URL(s) for the documentation of the symbol under the cursor.
411 pub fn external_docs(
413 position: FilePosition,
414 ) -> Cancelable<Option<doc_links::DocumentationLink>> {
415 self.with_db(|db| doc_links::external_docs(db, &position))
418 /// Computes parameter information for the given call expression.
419 pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
420 self.with_db(|db| ide_db::call_info::call_info(db, position))
423 /// Computes call hierarchy candidates for the given file position.
424 pub fn call_hierarchy(
426 position: FilePosition,
427 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
428 self.with_db(|db| call_hierarchy::call_hierarchy(db, position))
431 /// Computes incoming calls for the given file position.
432 pub fn incoming_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
433 self.with_db(|db| call_hierarchy::incoming_calls(db, position))
436 /// Computes incoming calls for the given file position.
437 pub fn outgoing_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
438 self.with_db(|db| call_hierarchy::outgoing_calls(db, position))
441 /// Returns a `mod name;` declaration which created the current module.
442 pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
443 self.with_db(|db| parent_module::parent_module(db, position))
446 /// Returns crates this file belongs too.
447 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
448 self.with_db(|db| parent_module::crate_for(db, file_id))
451 /// Returns the edition of the given crate.
452 pub fn crate_edition(&self, crate_id: CrateId) -> Cancelable<Edition> {
453 self.with_db(|db| db.crate_graph()[crate_id].edition)
456 /// Returns the root file of the given crate.
457 pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
458 self.with_db(|db| db.crate_graph()[crate_id].root_file_id)
461 /// Returns the set of possible targets to run for the current file.
462 pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
463 self.with_db(|db| runnables::runnables(db, file_id))
466 /// Returns the set of tests for the given file position.
467 pub fn related_tests(
469 position: FilePosition,
470 search_scope: Option<SearchScope>,
471 ) -> Cancelable<Vec<Runnable>> {
472 self.with_db(|db| runnables::related_tests(db, position, search_scope))
475 /// Computes syntax highlighting for the given file
476 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HlRange>> {
477 self.with_db(|db| syntax_highlighting::highlight(db, file_id, None, false))
480 /// Computes syntax highlighting for the given file range.
481 pub fn highlight_range(&self, frange: FileRange) -> Cancelable<Vec<HlRange>> {
483 syntax_highlighting::highlight(db, frange.file_id, Some(frange.range), false)
487 /// Computes syntax highlighting for the given file.
488 pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancelable<String> {
489 self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
492 /// Computes completions at the given position.
495 config: &CompletionConfig,
496 position: FilePosition,
497 ) -> Cancelable<Option<Vec<CompletionItem>>> {
498 self.with_db(|db| ide_completion::completions(db, config, position).map(Into::into))
501 /// Resolves additional completion data at the position given.
502 pub fn resolve_completion_edits(
504 config: &CompletionConfig,
505 position: FilePosition,
506 full_import_path: &str,
507 imported_name: String,
508 ) -> Cancelable<Vec<TextEdit>> {
511 ide_completion::resolve_completion_edits(
519 .unwrap_or_default())
522 /// Computes assists (aka code actions aka intentions) for the given
523 /// position. If `resolve == false`, computes enough info to show the
524 /// lightbulb list in the editor, but doesn't compute actual edits, to
525 /// improve performance.
528 config: &AssistConfig,
529 resolve: AssistResolveStrategy,
531 ) -> Cancelable<Vec<Assist>> {
533 let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
534 let mut acc = Assist::get(db, config, resolve, frange);
535 acc.extend(ssr_assists.into_iter());
540 /// Computes the set of diagnostics for the given file.
543 config: &DiagnosticsConfig,
544 resolve: AssistResolveStrategy,
546 ) -> Cancelable<Vec<Diagnostic>> {
547 self.with_db(|db| diagnostics::diagnostics(db, config, &resolve, file_id))
550 /// Convenience function to return assists + quick fixes for diagnostics
551 pub fn assists_with_fixes(
553 assist_config: &AssistConfig,
554 diagnostics_config: &DiagnosticsConfig,
555 resolve: AssistResolveStrategy,
557 ) -> Cancelable<Vec<Assist>> {
558 let include_fixes = match &assist_config.allowed {
559 Some(it) => it.iter().any(|&it| it == AssistKind::None || it == AssistKind::QuickFix),
564 let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
565 let diagnostic_assists = if include_fixes {
566 diagnostics::diagnostics(db, diagnostics_config, &resolve, frange.file_id)
568 .flat_map(|it| it.fixes.unwrap_or_default())
569 .filter(|it| it.target.intersect(frange.range).is_some())
575 let mut res = Assist::get(db, assist_config, resolve, frange);
576 res.extend(ssr_assists.into_iter());
577 res.extend(diagnostic_assists.into_iter());
583 /// Returns the edit required to rename reference at the position to the new
587 position: FilePosition,
589 ) -> Cancelable<Result<SourceChange, RenameError>> {
590 self.with_db(|db| references::rename::rename(db, position, new_name))
593 pub fn prepare_rename(
595 position: FilePosition,
596 ) -> Cancelable<Result<RangeInfo<()>, RenameError>> {
597 self.with_db(|db| references::rename::prepare_rename(db, position))
600 pub fn will_rename_file(
604 ) -> Cancelable<Option<SourceChange>> {
605 self.with_db(|db| references::rename::will_rename_file(db, file_id, new_name_stem))
608 pub fn structural_search_replace(
612 resolve_context: FilePosition,
613 selections: Vec<FileRange>,
614 ) -> Cancelable<Result<SourceChange, SsrError>> {
616 let rule: ide_ssr::SsrRule = query.parse()?;
617 let mut match_finder =
618 ide_ssr::MatchFinder::in_context(db, resolve_context, selections);
619 match_finder.add_rule(rule)?;
620 let edits = if parse_only { Default::default() } else { match_finder.edits() };
621 Ok(SourceChange::from(edits))
628 config: AnnotationConfig,
629 ) -> Cancelable<Vec<Annotation>> {
630 self.with_db(|db| annotations::annotations(db, file_id, config))
633 pub fn resolve_annotation(&self, annotation: Annotation) -> Cancelable<Annotation> {
634 self.with_db(|db| annotations::resolve_annotation(db, annotation))
640 direction: Direction,
641 ) -> Cancelable<Option<TextEdit>> {
642 self.with_db(|db| move_item::move_item(db, range, direction))
645 /// Performs an operation on that may be Canceled.
646 fn with_db<F, T>(&self, f: F) -> Cancelable<T>
648 F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
650 self.db.catch_canceled(f)
655 fn analysis_is_send() {
656 fn is_send<T: Send>() {}
657 is_send::<Analysis>();