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;
57 use ide_db::base_db::{
58 salsa::{self, ParallelDatabase},
59 CheckCanceled, Env, FileLoader, FileSet, SourceDatabase, VfsPath,
62 symbol_index::{self, FileSymbol},
65 use syntax::SourceFile;
67 use crate::display::ToNav;
70 annotations::{Annotation, AnnotationConfig, AnnotationKind},
71 call_hierarchy::CallItem,
72 diagnostics::{Diagnostic, DiagnosticsConfig, Fix, Severity},
73 display::navigation_target::NavigationTarget,
74 expand_macro::ExpandedMacro,
75 file_structure::{StructureNode, StructureNodeKind},
76 folding_ranges::{Fold, FoldKind},
77 hover::{HoverAction, HoverConfig, HoverGotoTypeData, HoverResult},
78 inlay_hints::{InlayHint, InlayHintsConfig, InlayKind},
81 prime_caches::PrimeCachesProgress,
82 references::{rename::RenameError, ReferenceSearchResult},
83 runnables::{Runnable, RunnableKind, TestId},
84 syntax_highlighting::{
85 tags::{Highlight, HlMod, HlMods, HlPunct, HlTag},
89 pub use hir::{Documentation, Semantics};
90 pub use ide_assists::{Assist, AssistConfig, AssistId, AssistKind};
91 pub use ide_completion::{
92 CompletionConfig, CompletionItem, CompletionItemKind, CompletionRelevance, ImportEdit,
97 Canceled, Change, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange,
98 SourceRoot, SourceRootId,
102 line_index::{LineCol, LineColUtf16, LineIndex},
103 search::{ReferenceAccess, SearchScope},
104 source_change::{FileSystemEdit, SourceChange},
106 RootDatabase, SymbolKind,
108 pub use ide_ssr::SsrError;
109 pub use syntax::{TextRange, TextSize};
110 pub use text_edit::{Indel, TextEdit};
112 pub type Cancelable<T> = Result<T, Canceled>;
114 /// Info associated with a text range.
116 pub struct RangeInfo<T> {
117 pub range: TextRange,
121 impl<T> RangeInfo<T> {
122 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
123 RangeInfo { range, info }
127 /// `AnalysisHost` stores the current state of the world.
129 pub struct AnalysisHost {
134 pub fn new(lru_capacity: Option<usize>) -> AnalysisHost {
135 AnalysisHost { db: RootDatabase::new(lru_capacity) }
138 pub fn update_lru_capacity(&mut self, lru_capacity: Option<usize>) {
139 self.db.update_lru_capacity(lru_capacity);
142 /// Returns a snapshot of the current state, which you can query for
143 /// semantic information.
144 pub fn analysis(&self) -> Analysis {
145 Analysis { db: self.db.snapshot() }
148 /// Applies changes to the current state of the world. If there are
149 /// outstanding snapshots, they will be canceled.
150 pub fn apply_change(&mut self, change: Change) {
151 self.db.apply_change(change)
154 pub fn collect_garbage(&mut self) {
155 self.db.collect_garbage();
157 /// NB: this clears the database
158 pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes)> {
159 self.db.per_query_memory_usage()
161 pub fn request_cancellation(&mut self) {
162 self.db.request_cancellation();
164 pub fn raw_database(&self) -> &RootDatabase {
167 pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
172 impl Default for AnalysisHost {
173 fn default() -> AnalysisHost {
174 AnalysisHost::new(None)
178 /// Analysis is a snapshot of a world state at a moment in time. It is the main
179 /// entry point for asking semantic information about the world. When the world
180 /// state is advanced using `AnalysisHost::apply_change` method, all existing
181 /// `Analysis` are canceled (most method return `Err(Canceled)`).
183 pub struct Analysis {
184 db: salsa::Snapshot<RootDatabase>,
187 // As a general design guideline, `Analysis` API are intended to be independent
188 // from the language server protocol. That is, when exposing some functionality
189 // we should think in terms of "what API makes most sense" and not in terms of
190 // "what types LSP uses". Although currently LSP is the only consumer of the
191 // API, the API should in theory be usable as a library, or via a different
194 // Creates an analysis instance for a single file, without any extenal
195 // dependencies, stdlib support or ability to apply changes. See
196 // `AnalysisHost` for creating a fully-featured analysis.
197 pub fn from_single_file(text: String) -> (Analysis, FileId) {
198 let mut host = AnalysisHost::default();
199 let file_id = FileId(0);
200 let mut file_set = FileSet::default();
201 file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_string()));
202 let source_root = SourceRoot::new_local(file_set);
204 let mut change = Change::new();
205 change.set_roots(vec![source_root]);
206 let mut crate_graph = CrateGraph::default();
207 // FIXME: cfg options
208 // Default to enable test for single file.
209 let mut cfg_options = CfgOptions::default();
210 cfg_options.insert_atom("test".into());
211 crate_graph.add_crate_root(
213 Edition::Edition2018,
219 change.change_file(file_id, Some(Arc::new(text)));
220 change.set_crate_graph(crate_graph);
221 host.apply_change(change);
222 (host.analysis(), file_id)
225 /// Debug info about the current state of the analysis.
226 pub fn status(&self, file_id: Option<FileId>) -> Cancelable<String> {
227 self.with_db(|db| status::status(&*db, file_id))
230 pub fn prime_caches<F>(&self, cb: F) -> Cancelable<()>
232 F: Fn(PrimeCachesProgress) + Sync + std::panic::UnwindSafe,
234 self.with_db(move |db| prime_caches::prime_caches(db, &cb))
237 /// Gets the text of the source file.
238 pub fn file_text(&self, file_id: FileId) -> Cancelable<Arc<String>> {
239 self.with_db(|db| db.file_text(file_id))
242 /// Gets the syntax tree of the file.
243 pub fn parse(&self, file_id: FileId) -> Cancelable<SourceFile> {
244 self.with_db(|db| db.parse(file_id).tree())
247 /// Gets the file's `LineIndex`: data structure to convert between absolute
248 /// offsets and line/column representation.
249 pub fn file_line_index(&self, file_id: FileId) -> Cancelable<Arc<LineIndex>> {
250 self.with_db(|db| db.line_index(file_id))
253 /// Selects the next syntactic nodes encompassing the range.
254 pub fn extend_selection(&self, frange: FileRange) -> Cancelable<TextRange> {
255 self.with_db(|db| extend_selection::extend_selection(db, frange))
258 /// Returns position of the matching brace (all types of braces are
260 pub fn matching_brace(&self, position: FilePosition) -> Cancelable<Option<TextSize>> {
262 let parse = db.parse(position.file_id);
263 let file = parse.tree();
264 matching_brace::matching_brace(&file, position.offset)
268 /// Returns a syntax tree represented as `String`, for debug purposes.
269 // FIXME: use a better name here.
273 text_range: Option<TextRange>,
274 ) -> Cancelable<String> {
275 self.with_db(|db| syntax_tree::syntax_tree(&db, file_id, text_range))
278 pub fn view_hir(&self, position: FilePosition) -> Cancelable<String> {
279 self.with_db(|db| view_hir::view_hir(&db, position))
282 pub fn expand_macro(&self, position: FilePosition) -> Cancelable<Option<ExpandedMacro>> {
283 self.with_db(|db| expand_macro::expand_macro(db, position))
286 /// Returns an edit to remove all newlines in the range, cleaning up minor
287 /// stuff like trailing commas.
288 pub fn join_lines(&self, frange: FileRange) -> Cancelable<TextEdit> {
290 let parse = db.parse(frange.file_id);
291 join_lines::join_lines(&parse.tree(), frange.range)
295 /// Returns an edit which should be applied when opening a new line, fixing
296 /// up minor stuff like continuing the comment.
297 /// The edit will be a snippet (with `$0`).
298 pub fn on_enter(&self, position: FilePosition) -> Cancelable<Option<TextEdit>> {
299 self.with_db(|db| typing::on_enter(&db, position))
302 /// Returns an edit which should be applied after a character was typed.
304 /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
306 pub fn on_char_typed(
308 position: FilePosition,
310 ) -> Cancelable<Option<SourceChange>> {
311 // Fast path to not even parse the file.
312 if !typing::TRIGGER_CHARS.contains(char_typed) {
315 self.with_db(|db| typing::on_char_typed(&db, position, char_typed))
318 /// Returns a tree representation of symbols in the file. Useful to draw a
320 pub fn file_structure(&self, file_id: FileId) -> Cancelable<Vec<StructureNode>> {
321 self.with_db(|db| file_structure::file_structure(&db.parse(file_id).tree()))
324 /// Returns a list of the places in the file where type hints can be displayed.
328 config: &InlayHintsConfig,
329 ) -> Cancelable<Vec<InlayHint>> {
330 self.with_db(|db| inlay_hints::inlay_hints(db, file_id, config))
333 /// Returns the set of folding ranges.
334 pub fn folding_ranges(&self, file_id: FileId) -> Cancelable<Vec<Fold>> {
335 self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
338 /// Fuzzy searches for a symbol.
339 pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
341 symbol_index::world_symbols(db, query)
343 .map(|s| s.to_nav(db))
348 /// Returns the definitions from the symbol at `position`.
349 pub fn goto_definition(
351 position: FilePosition,
352 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
353 self.with_db(|db| goto_definition::goto_definition(db, position))
356 /// Returns the impls from the symbol at `position`.
357 pub fn goto_implementation(
359 position: FilePosition,
360 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
361 self.with_db(|db| goto_implementation::goto_implementation(db, position))
364 /// Returns the type definitions for the symbol at `position`.
365 pub fn goto_type_definition(
367 position: FilePosition,
368 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
369 self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
372 /// Finds all usages of the reference at point.
373 pub fn find_all_refs(
375 position: FilePosition,
376 search_scope: Option<SearchScope>,
377 ) -> Cancelable<Option<ReferenceSearchResult>> {
378 self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, search_scope))
381 /// Finds all methods and free functions for the file. Does not return tests!
382 pub fn find_all_methods(&self, file_id: FileId) -> Cancelable<Vec<FileRange>> {
383 self.with_db(|db| fn_references::find_all_methods(db, file_id))
386 /// Returns a short text describing element at position.
389 position: FilePosition,
390 links_in_hover: bool,
392 ) -> Cancelable<Option<RangeInfo<HoverResult>>> {
393 self.with_db(|db| hover::hover(db, position, links_in_hover, markdown))
396 /// Return URL(s) for the documentation of the symbol under the cursor.
397 pub fn external_docs(
399 position: FilePosition,
400 ) -> Cancelable<Option<doc_links::DocumentationLink>> {
401 self.with_db(|db| doc_links::external_docs(db, &position))
404 /// Computes parameter information for the given call expression.
405 pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
406 self.with_db(|db| ide_db::call_info::call_info(db, position))
409 /// Computes call hierarchy candidates for the given file position.
410 pub fn call_hierarchy(
412 position: FilePosition,
413 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
414 self.with_db(|db| call_hierarchy::call_hierarchy(db, position))
417 /// Computes incoming calls for the given file position.
418 pub fn incoming_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
419 self.with_db(|db| call_hierarchy::incoming_calls(db, position))
422 /// Computes incoming calls for the given file position.
423 pub fn outgoing_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
424 self.with_db(|db| call_hierarchy::outgoing_calls(db, position))
427 /// Returns a `mod name;` declaration which created the current module.
428 pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
429 self.with_db(|db| parent_module::parent_module(db, position))
432 /// Returns crates this file belongs too.
433 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
434 self.with_db(|db| parent_module::crate_for(db, file_id))
437 /// Returns the edition of the given crate.
438 pub fn crate_edition(&self, crate_id: CrateId) -> Cancelable<Edition> {
439 self.with_db(|db| db.crate_graph()[crate_id].edition)
442 /// Returns the root file of the given crate.
443 pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
444 self.with_db(|db| db.crate_graph()[crate_id].root_file_id)
447 /// Returns the set of possible targets to run for the current file.
448 pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
449 self.with_db(|db| runnables::runnables(db, file_id))
452 /// Returns the set of tests for the given file position.
453 pub fn related_tests(
455 position: FilePosition,
456 search_scope: Option<SearchScope>,
457 ) -> Cancelable<Vec<Runnable>> {
458 self.with_db(|db| runnables::related_tests(db, position, search_scope))
461 /// Computes syntax highlighting for the given file
462 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HlRange>> {
463 self.with_db(|db| syntax_highlighting::highlight(db, file_id, None, false))
466 /// Computes syntax highlighting for the given file range.
467 pub fn highlight_range(&self, frange: FileRange) -> Cancelable<Vec<HlRange>> {
469 syntax_highlighting::highlight(db, frange.file_id, Some(frange.range), false)
473 /// Computes syntax highlighting for the given file.
474 pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancelable<String> {
475 self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
478 /// Computes completions at the given position.
481 config: &CompletionConfig,
482 position: FilePosition,
483 ) -> Cancelable<Option<Vec<CompletionItem>>> {
484 self.with_db(|db| ide_completion::completions(db, config, position).map(Into::into))
487 /// Resolves additional completion data at the position given.
488 pub fn resolve_completion_edits(
490 config: &CompletionConfig,
491 position: FilePosition,
492 full_import_path: &str,
493 imported_name: String,
494 ) -> Cancelable<Vec<TextEdit>> {
497 ide_completion::resolve_completion_edits(
505 .unwrap_or_default())
508 /// Computes assists (aka code actions aka intentions) for the given
509 /// position. If `resolve == false`, computes enough info to show the
510 /// lightbulb list in the editor, but doesn't compute actual edits, to
511 /// improve performance.
514 config: &AssistConfig,
517 ) -> Cancelable<Vec<Assist>> {
519 let mut acc = Assist::get(db, config, resolve, frange);
520 ssr::add_ssr_assist(db, &mut acc, resolve, frange);
525 /// Computes the set of diagnostics for the given file.
528 config: &DiagnosticsConfig,
530 ) -> Cancelable<Vec<Diagnostic>> {
531 self.with_db(|db| diagnostics::diagnostics(db, config, file_id))
534 /// Returns the edit required to rename reference at the position to the new
538 position: FilePosition,
540 ) -> Cancelable<Result<SourceChange, RenameError>> {
541 self.with_db(|db| references::rename::rename(db, position, new_name))
544 pub fn prepare_rename(
546 position: FilePosition,
547 ) -> Cancelable<Result<RangeInfo<()>, RenameError>> {
548 self.with_db(|db| references::rename::prepare_rename(db, position))
551 pub fn will_rename_file(
555 ) -> Cancelable<Option<SourceChange>> {
556 self.with_db(|db| references::rename::will_rename_file(db, file_id, new_name_stem))
559 pub fn structural_search_replace(
563 resolve_context: FilePosition,
564 selections: Vec<FileRange>,
565 ) -> Cancelable<Result<SourceChange, SsrError>> {
567 let rule: ide_ssr::SsrRule = query.parse()?;
568 let mut match_finder =
569 ide_ssr::MatchFinder::in_context(db, resolve_context, selections);
570 match_finder.add_rule(rule)?;
571 let edits = if parse_only { Default::default() } else { match_finder.edits() };
572 Ok(SourceChange::from(edits))
579 config: AnnotationConfig,
580 ) -> Cancelable<Vec<Annotation>> {
581 self.with_db(|db| annotations::annotations(db, file_id, config))
584 pub fn resolve_annotation(&self, annotation: Annotation) -> Cancelable<Annotation> {
585 self.with_db(|db| annotations::resolve_annotation(db, annotation))
591 direction: Direction,
592 ) -> Cancelable<Option<TextEdit>> {
593 self.with_db(|db| move_item::move_item(db, range, direction))
596 /// Performs an operation on that may be Canceled.
597 fn with_db<F, T>(&self, f: F) -> Cancelable<T>
599 F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
601 self.db.catch_canceled(f)
606 fn analysis_is_send() {
607 fn is_send<T: Send>() {}
608 is_send::<Analysis>();