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;
45 mod syntax_highlighting;
54 use ide_db::base_db::{
55 salsa::{self, ParallelDatabase},
56 CheckCanceled, Env, FileLoader, FileSet, SourceDatabase, VfsPath,
59 symbol_index::{self, FileSymbol},
62 use syntax::SourceFile;
64 use crate::display::ToNav;
67 annotations::{Annotation, AnnotationConfig, AnnotationKind},
68 call_hierarchy::CallItem,
69 diagnostics::{Diagnostic, DiagnosticsConfig, Fix, Severity},
70 display::navigation_target::NavigationTarget,
71 expand_macro::ExpandedMacro,
72 file_structure::StructureNode,
73 folding_ranges::{Fold, FoldKind},
74 hover::{HoverAction, HoverConfig, HoverGotoTypeData, HoverResult},
75 inlay_hints::{InlayHint, InlayHintsConfig, InlayKind},
77 prime_caches::PrimeCachesProgress,
78 references::{rename::RenameError, ReferenceSearchResult},
79 runnables::{Runnable, RunnableKind, TestId},
80 syntax_highlighting::{
81 tags::{Highlight, HlMod, HlMods, HlPunct, HlTag},
85 pub use hir::{Documentation, Semantics};
86 pub use ide_assists::{Assist, AssistConfig, AssistId, AssistKind};
87 pub use ide_completion::{
88 CompletionConfig, CompletionItem, CompletionItemKind, CompletionScore, ImportEdit,
93 Canceled, Change, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange,
94 SourceRoot, SourceRootId,
98 line_index::{LineCol, LineColUtf16, LineIndex},
99 search::{ReferenceAccess, SearchScope},
100 source_change::{FileSystemEdit, SourceChange},
104 pub use ide_ssr::SsrError;
105 pub use syntax::{TextRange, TextSize};
106 pub use text_edit::{Indel, TextEdit};
108 pub type Cancelable<T> = Result<T, Canceled>;
110 /// Info associated with a text range.
112 pub struct RangeInfo<T> {
113 pub range: TextRange,
117 impl<T> RangeInfo<T> {
118 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
119 RangeInfo { range, info }
123 /// `AnalysisHost` stores the current state of the world.
125 pub struct AnalysisHost {
130 pub fn new(lru_capacity: Option<usize>) -> AnalysisHost {
131 AnalysisHost { db: RootDatabase::new(lru_capacity) }
134 pub fn update_lru_capacity(&mut self, lru_capacity: Option<usize>) {
135 self.db.update_lru_capacity(lru_capacity);
138 /// Returns a snapshot of the current state, which you can query for
139 /// semantic information.
140 pub fn analysis(&self) -> Analysis {
141 Analysis { db: self.db.snapshot() }
144 /// Applies changes to the current state of the world. If there are
145 /// outstanding snapshots, they will be canceled.
146 pub fn apply_change(&mut self, change: Change) {
147 self.db.apply_change(change)
150 pub fn collect_garbage(&mut self) {
151 self.db.collect_garbage();
153 /// NB: this clears the database
154 pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes)> {
155 self.db.per_query_memory_usage()
157 pub fn request_cancellation(&mut self) {
158 self.db.request_cancellation();
160 pub fn raw_database(&self) -> &RootDatabase {
163 pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
168 impl Default for AnalysisHost {
169 fn default() -> AnalysisHost {
170 AnalysisHost::new(None)
174 /// Analysis is a snapshot of a world state at a moment in time. It is the main
175 /// entry point for asking semantic information about the world. When the world
176 /// state is advanced using `AnalysisHost::apply_change` method, all existing
177 /// `Analysis` are canceled (most method return `Err(Canceled)`).
179 pub struct Analysis {
180 db: salsa::Snapshot<RootDatabase>,
183 // As a general design guideline, `Analysis` API are intended to be independent
184 // from the language server protocol. That is, when exposing some functionality
185 // we should think in terms of "what API makes most sense" and not in terms of
186 // "what types LSP uses". Although currently LSP is the only consumer of the
187 // API, the API should in theory be usable as a library, or via a different
190 // Creates an analysis instance for a single file, without any extenal
191 // dependencies, stdlib support or ability to apply changes. See
192 // `AnalysisHost` for creating a fully-featured analysis.
193 pub fn from_single_file(text: String) -> (Analysis, FileId) {
194 let mut host = AnalysisHost::default();
195 let file_id = FileId(0);
196 let mut file_set = FileSet::default();
197 file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_string()));
198 let source_root = SourceRoot::new_local(file_set);
200 let mut change = Change::new();
201 change.set_roots(vec![source_root]);
202 let mut crate_graph = CrateGraph::default();
203 // FIXME: cfg options
204 // Default to enable test for single file.
205 let mut cfg_options = CfgOptions::default();
206 cfg_options.insert_atom("test".into());
207 crate_graph.add_crate_root(
209 Edition::Edition2018,
215 change.change_file(file_id, Some(Arc::new(text)));
216 change.set_crate_graph(crate_graph);
217 host.apply_change(change);
218 (host.analysis(), file_id)
221 /// Debug info about the current state of the analysis.
222 pub fn status(&self, file_id: Option<FileId>) -> Cancelable<String> {
223 self.with_db(|db| status::status(&*db, file_id))
226 pub fn prime_caches<F>(&self, cb: F) -> Cancelable<()>
228 F: Fn(PrimeCachesProgress) + Sync + std::panic::UnwindSafe,
230 self.with_db(move |db| prime_caches::prime_caches(db, &cb))
233 /// Gets the text of the source file.
234 pub fn file_text(&self, file_id: FileId) -> Cancelable<Arc<String>> {
235 self.with_db(|db| db.file_text(file_id))
238 /// Gets the syntax tree of the file.
239 pub fn parse(&self, file_id: FileId) -> Cancelable<SourceFile> {
240 self.with_db(|db| db.parse(file_id).tree())
243 /// Gets the file's `LineIndex`: data structure to convert between absolute
244 /// offsets and line/column representation.
245 pub fn file_line_index(&self, file_id: FileId) -> Cancelable<Arc<LineIndex>> {
246 self.with_db(|db| db.line_index(file_id))
249 /// Selects the next syntactic nodes encompassing the range.
250 pub fn extend_selection(&self, frange: FileRange) -> Cancelable<TextRange> {
251 self.with_db(|db| extend_selection::extend_selection(db, frange))
254 /// Returns position of the matching brace (all types of braces are
256 pub fn matching_brace(&self, position: FilePosition) -> Cancelable<Option<TextSize>> {
258 let parse = db.parse(position.file_id);
259 let file = parse.tree();
260 matching_brace::matching_brace(&file, position.offset)
264 /// Returns a syntax tree represented as `String`, for debug purposes.
265 // FIXME: use a better name here.
269 text_range: Option<TextRange>,
270 ) -> Cancelable<String> {
271 self.with_db(|db| syntax_tree::syntax_tree(&db, file_id, text_range))
274 pub fn view_hir(&self, position: FilePosition) -> Cancelable<String> {
275 self.with_db(|db| view_hir::view_hir(&db, position))
278 pub fn expand_macro(&self, position: FilePosition) -> Cancelable<Option<ExpandedMacro>> {
279 self.with_db(|db| expand_macro::expand_macro(db, position))
282 /// Returns an edit to remove all newlines in the range, cleaning up minor
283 /// stuff like trailing commas.
284 pub fn join_lines(&self, frange: FileRange) -> Cancelable<TextEdit> {
286 let parse = db.parse(frange.file_id);
287 join_lines::join_lines(&parse.tree(), frange.range)
291 /// Returns an edit which should be applied when opening a new line, fixing
292 /// up minor stuff like continuing the comment.
293 /// The edit will be a snippet (with `$0`).
294 pub fn on_enter(&self, position: FilePosition) -> Cancelable<Option<TextEdit>> {
295 self.with_db(|db| typing::on_enter(&db, position))
298 /// Returns an edit which should be applied after a character was typed.
300 /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
302 pub fn on_char_typed(
304 position: FilePosition,
306 ) -> Cancelable<Option<SourceChange>> {
307 // Fast path to not even parse the file.
308 if !typing::TRIGGER_CHARS.contains(char_typed) {
311 self.with_db(|db| typing::on_char_typed(&db, position, char_typed))
314 /// Returns a tree representation of symbols in the file. Useful to draw a
316 pub fn file_structure(&self, file_id: FileId) -> Cancelable<Vec<StructureNode>> {
317 self.with_db(|db| file_structure::file_structure(&db.parse(file_id).tree()))
320 /// Returns a list of the places in the file where type hints can be displayed.
324 config: &InlayHintsConfig,
325 ) -> Cancelable<Vec<InlayHint>> {
326 self.with_db(|db| inlay_hints::inlay_hints(db, file_id, config))
329 /// Returns the set of folding ranges.
330 pub fn folding_ranges(&self, file_id: FileId) -> Cancelable<Vec<Fold>> {
331 self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
334 /// Fuzzy searches for a symbol.
335 pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
337 symbol_index::world_symbols(db, query)
339 .map(|s| s.to_nav(db))
344 /// Returns the definitions from the symbol at `position`.
345 pub fn goto_definition(
347 position: FilePosition,
348 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
349 self.with_db(|db| goto_definition::goto_definition(db, position))
352 /// Returns the impls from the symbol at `position`.
353 pub fn goto_implementation(
355 position: FilePosition,
356 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
357 self.with_db(|db| goto_implementation::goto_implementation(db, position))
360 /// Returns the type definitions for the symbol at `position`.
361 pub fn goto_type_definition(
363 position: FilePosition,
364 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
365 self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
368 /// Finds all usages of the reference at point.
369 pub fn find_all_refs(
371 position: FilePosition,
372 search_scope: Option<SearchScope>,
373 ) -> Cancelable<Option<ReferenceSearchResult>> {
374 self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, search_scope))
377 /// Finds all methods and free functions for the file. Does not return tests!
378 pub fn find_all_methods(&self, file_id: FileId) -> Cancelable<Vec<FileRange>> {
379 self.with_db(|db| fn_references::find_all_methods(db, file_id))
382 /// Returns a short text describing element at position.
385 position: FilePosition,
386 links_in_hover: bool,
388 ) -> Cancelable<Option<RangeInfo<HoverResult>>> {
389 self.with_db(|db| hover::hover(db, position, links_in_hover, markdown))
392 /// Return URL(s) for the documentation of the symbol under the cursor.
393 pub fn external_docs(
395 position: FilePosition,
396 ) -> Cancelable<Option<doc_links::DocumentationLink>> {
397 self.with_db(|db| doc_links::external_docs(db, &position))
400 /// Computes parameter information for the given call expression.
401 pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
402 self.with_db(|db| ide_db::call_info::call_info(db, position))
405 /// Computes call hierarchy candidates for the given file position.
406 pub fn call_hierarchy(
408 position: FilePosition,
409 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
410 self.with_db(|db| call_hierarchy::call_hierarchy(db, position))
413 /// Computes incoming calls for the given file position.
414 pub fn incoming_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
415 self.with_db(|db| call_hierarchy::incoming_calls(db, position))
418 /// Computes incoming calls for the given file position.
419 pub fn outgoing_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
420 self.with_db(|db| call_hierarchy::outgoing_calls(db, position))
423 /// Returns a `mod name;` declaration which created the current module.
424 pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
425 self.with_db(|db| parent_module::parent_module(db, position))
428 /// Returns crates this file belongs too.
429 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
430 self.with_db(|db| parent_module::crate_for(db, file_id))
433 /// Returns the edition of the given crate.
434 pub fn crate_edition(&self, crate_id: CrateId) -> Cancelable<Edition> {
435 self.with_db(|db| db.crate_graph()[crate_id].edition)
438 /// Returns the root file of the given crate.
439 pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
440 self.with_db(|db| db.crate_graph()[crate_id].root_file_id)
443 /// Returns the set of possible targets to run for the current file.
444 pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
445 self.with_db(|db| runnables::runnables(db, file_id))
448 /// Computes syntax highlighting for the given file
449 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HlRange>> {
450 self.with_db(|db| syntax_highlighting::highlight(db, file_id, None, false))
453 /// Computes syntax highlighting for the given file range.
454 pub fn highlight_range(&self, frange: FileRange) -> Cancelable<Vec<HlRange>> {
456 syntax_highlighting::highlight(db, frange.file_id, Some(frange.range), false)
460 /// Computes syntax highlighting for the given file.
461 pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancelable<String> {
462 self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
465 /// Computes completions at the given position.
468 config: &CompletionConfig,
469 position: FilePosition,
470 ) -> Cancelable<Option<Vec<CompletionItem>>> {
471 self.with_db(|db| ide_completion::completions(db, config, position).map(Into::into))
474 /// Resolves additional completion data at the position given.
475 pub fn resolve_completion_edits(
477 config: &CompletionConfig,
478 position: FilePosition,
479 full_import_path: &str,
480 imported_name: String,
481 ) -> Cancelable<Vec<TextEdit>> {
484 ide_completion::resolve_completion_edits(
492 .unwrap_or_default())
495 /// Computes assists (aka code actions aka intentions) for the given
496 /// position. If `resolve == false`, computes enough info to show the
497 /// lightbulb list in the editor, but doesn't compute actual edits, to
498 /// improve performance.
501 config: &AssistConfig,
504 ) -> Cancelable<Vec<Assist>> {
505 self.with_db(|db| Assist::get(db, config, resolve, frange))
508 /// Computes the set of diagnostics for the given file.
511 config: &DiagnosticsConfig,
513 ) -> Cancelable<Vec<Diagnostic>> {
514 self.with_db(|db| diagnostics::diagnostics(db, config, file_id))
517 /// Returns the edit required to rename reference at the position to the new
521 position: FilePosition,
523 ) -> Cancelable<Result<SourceChange, RenameError>> {
524 self.with_db(|db| references::rename::rename(db, position, new_name))
527 pub fn prepare_rename(
529 position: FilePosition,
530 ) -> Cancelable<Result<RangeInfo<()>, RenameError>> {
531 self.with_db(|db| references::rename::prepare_rename(db, position))
534 pub fn will_rename_file(
538 ) -> Cancelable<Option<SourceChange>> {
539 self.with_db(|db| references::rename::will_rename_file(db, file_id, new_name_stem))
542 pub fn structural_search_replace(
546 resolve_context: FilePosition,
547 selections: Vec<FileRange>,
548 ) -> Cancelable<Result<SourceChange, SsrError>> {
550 let rule: ide_ssr::SsrRule = query.parse()?;
551 let mut match_finder =
552 ide_ssr::MatchFinder::in_context(db, resolve_context, selections);
553 match_finder.add_rule(rule)?;
554 let edits = if parse_only { Default::default() } else { match_finder.edits() };
555 Ok(SourceChange::from(edits))
562 config: AnnotationConfig,
563 ) -> Cancelable<Vec<Annotation>> {
564 self.with_db(|db| annotations::annotations(db, file_id, config))
567 pub fn resolve_annotation(&self, annotation: Annotation) -> Cancelable<Annotation> {
568 self.with_db(|db| annotations::resolve_annotation(db, annotation))
571 /// Performs an operation on that may be Canceled.
572 fn with_db<F, T>(&self, f: F) -> Cancelable<T>
574 F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
576 self.db.catch_canceled(f)
581 fn analysis_is_send() {
582 fn is_send<T: Send>() {}
583 is_send::<Analysis>();