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)*) };
34 mod goto_implementation;
35 mod goto_type_definition;
45 mod syntax_highlighting;
53 salsa::{self, ParallelDatabase},
54 CheckCanceled, Env, FileLoader, FileSet, SourceDatabase, VfsPath,
58 symbol_index::{self, FileSymbol},
61 use syntax::{SourceFile, TextRange, TextSize};
63 use crate::display::ToNav;
66 call_hierarchy::CallItem,
69 CompletionConfig, CompletionItem, CompletionItemKind, CompletionScore, InsertTextFormat,
71 diagnostics::{Diagnostic, DiagnosticsConfig, Fix, Severity},
72 display::NavigationTarget,
73 expand_macro::ExpandedMacro,
74 file_structure::StructureNode,
75 folding_ranges::{Fold, FoldKind},
76 hover::{HoverAction, HoverConfig, HoverGotoTypeData, HoverResult},
77 inlay_hints::{InlayHint, InlayHintsConfig, InlayKind},
79 references::{Declaration, Reference, ReferenceAccess, ReferenceKind, ReferenceSearchResult},
80 runnables::{Runnable, RunnableKind, TestId},
81 syntax_highlighting::{
82 Highlight, HighlightModifier, HighlightModifiers, HighlightTag, HighlightedRange,
87 utils::MergeBehaviour, Assist, AssistConfig, AssistId, AssistKind, ResolvedAssist,
90 Canceled, Change, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange, SourceRoot,
93 pub use hir::{Documentation, Semantics};
96 line_index::{LineCol, LineIndex},
98 source_change::{FileSystemEdit, SourceChange, SourceFileEdit},
102 pub use ssr::SsrError;
103 pub use text_edit::{Indel, TextEdit};
105 pub type Cancelable<T> = Result<T, Canceled>;
107 /// Info associated with a text range.
109 pub struct RangeInfo<T> {
110 pub range: TextRange,
114 impl<T> RangeInfo<T> {
115 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
116 RangeInfo { range, info }
120 /// `AnalysisHost` stores the current state of the world.
122 pub struct AnalysisHost {
127 pub fn new(lru_capacity: Option<usize>) -> AnalysisHost {
128 AnalysisHost { db: RootDatabase::new(lru_capacity) }
131 pub fn update_lru_capacity(&mut self, lru_capacity: Option<usize>) {
132 self.db.update_lru_capacity(lru_capacity);
135 /// Returns a snapshot of the current state, which you can query for
136 /// semantic information.
137 pub fn analysis(&self) -> Analysis {
138 Analysis { db: self.db.snapshot() }
141 /// Applies changes to the current state of the world. If there are
142 /// outstanding snapshots, they will be canceled.
143 pub fn apply_change(&mut self, change: Change) {
144 self.db.apply_change(change)
147 pub fn collect_garbage(&mut self) {
148 self.db.collect_garbage();
150 /// NB: this clears the database
151 pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes)> {
152 self.db.per_query_memory_usage()
154 pub fn request_cancellation(&mut self) {
155 self.db.request_cancellation();
157 pub fn raw_database(&self) -> &RootDatabase {
160 pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
165 impl Default for AnalysisHost {
166 fn default() -> AnalysisHost {
167 AnalysisHost::new(None)
171 /// Analysis is a snapshot of a world state at a moment in time. It is the main
172 /// entry point for asking semantic information about the world. When the world
173 /// state is advanced using `AnalysisHost::apply_change` method, all existing
174 /// `Analysis` are canceled (most method return `Err(Canceled)`).
176 pub struct Analysis {
177 db: salsa::Snapshot<RootDatabase>,
180 // As a general design guideline, `Analysis` API are intended to be independent
181 // from the language server protocol. That is, when exposing some functionality
182 // we should think in terms of "what API makes most sense" and not in terms of
183 // "what types LSP uses". Although currently LSP is the only consumer of the
184 // API, the API should in theory be usable as a library, or via a different
187 // Creates an analysis instance for a single file, without any extenal
188 // dependencies, stdlib support or ability to apply changes. See
189 // `AnalysisHost` for creating a fully-featured analysis.
190 pub fn from_single_file(text: String) -> (Analysis, FileId) {
191 let mut host = AnalysisHost::default();
192 let file_id = FileId(0);
193 let mut file_set = FileSet::default();
194 file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_string()));
195 let source_root = SourceRoot::new_local(file_set);
197 let mut change = Change::new();
198 change.set_roots(vec![source_root]);
199 let mut crate_graph = CrateGraph::default();
200 // FIXME: cfg options
201 // Default to enable test for single file.
202 let mut cfg_options = CfgOptions::default();
203 cfg_options.insert_atom("test".into());
204 crate_graph.add_crate_root(
206 Edition::Edition2018,
212 change.change_file(file_id, Some(Arc::new(text)));
213 change.set_crate_graph(crate_graph);
214 host.apply_change(change);
215 (host.analysis(), file_id)
218 /// Debug info about the current state of the analysis.
219 pub fn status(&self, file_id: Option<FileId>) -> Cancelable<String> {
220 self.with_db(|db| status::status(&*db, file_id))
223 pub fn prime_caches(&self, files: Vec<FileId>) -> Cancelable<()> {
224 self.with_db(|db| prime_caches::prime_caches(db, files))
227 /// Gets the text of the source file.
228 pub fn file_text(&self, file_id: FileId) -> Cancelable<Arc<String>> {
229 self.with_db(|db| db.file_text(file_id))
232 /// Gets the syntax tree of the file.
233 pub fn parse(&self, file_id: FileId) -> Cancelable<SourceFile> {
234 self.with_db(|db| db.parse(file_id).tree())
237 /// Gets the file's `LineIndex`: data structure to convert between absolute
238 /// offsets and line/column representation.
239 pub fn file_line_index(&self, file_id: FileId) -> Cancelable<Arc<LineIndex>> {
240 self.with_db(|db| db.line_index(file_id))
243 /// Selects the next syntactic nodes encompassing the range.
244 pub fn extend_selection(&self, frange: FileRange) -> Cancelable<TextRange> {
245 self.with_db(|db| extend_selection::extend_selection(db, frange))
248 /// Returns position of the matching brace (all types of braces are
250 pub fn matching_brace(&self, position: FilePosition) -> Cancelable<Option<TextSize>> {
252 let parse = db.parse(position.file_id);
253 let file = parse.tree();
254 matching_brace::matching_brace(&file, position.offset)
258 /// Returns a syntax tree represented as `String`, for debug purposes.
259 // FIXME: use a better name here.
263 text_range: Option<TextRange>,
264 ) -> Cancelable<String> {
265 self.with_db(|db| syntax_tree::syntax_tree(&db, file_id, text_range))
268 pub fn expand_macro(&self, position: FilePosition) -> Cancelable<Option<ExpandedMacro>> {
269 self.with_db(|db| expand_macro::expand_macro(db, position))
272 /// Returns an edit to remove all newlines in the range, cleaning up minor
273 /// stuff like trailing commas.
274 pub fn join_lines(&self, frange: FileRange) -> Cancelable<TextEdit> {
276 let parse = db.parse(frange.file_id);
277 join_lines::join_lines(&parse.tree(), frange.range)
281 /// Returns an edit which should be applied when opening a new line, fixing
282 /// up minor stuff like continuing the comment.
283 /// The edit will be a snippet (with `$0`).
284 pub fn on_enter(&self, position: FilePosition) -> Cancelable<Option<TextEdit>> {
285 self.with_db(|db| typing::on_enter(&db, position))
288 /// Returns an edit which should be applied after a character was typed.
290 /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
292 pub fn on_char_typed(
294 position: FilePosition,
296 ) -> Cancelable<Option<SourceChange>> {
297 // Fast path to not even parse the file.
298 if !typing::TRIGGER_CHARS.contains(char_typed) {
301 self.with_db(|db| typing::on_char_typed(&db, position, char_typed))
304 /// Returns a tree representation of symbols in the file. Useful to draw a
306 pub fn file_structure(&self, file_id: FileId) -> Cancelable<Vec<StructureNode>> {
307 self.with_db(|db| file_structure::file_structure(&db.parse(file_id).tree()))
310 /// Returns a list of the places in the file where type hints can be displayed.
314 config: &InlayHintsConfig,
315 ) -> Cancelable<Vec<InlayHint>> {
316 self.with_db(|db| inlay_hints::inlay_hints(db, file_id, config))
319 /// Returns the set of folding ranges.
320 pub fn folding_ranges(&self, file_id: FileId) -> Cancelable<Vec<Fold>> {
321 self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
324 /// Fuzzy searches for a symbol.
325 pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
327 symbol_index::world_symbols(db, query)
329 .map(|s| s.to_nav(db))
334 /// Returns the definitions from the symbol at `position`.
335 pub fn goto_definition(
337 position: FilePosition,
338 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
339 self.with_db(|db| goto_definition::goto_definition(db, position))
342 /// Returns the impls from the symbol at `position`.
343 pub fn goto_implementation(
345 position: FilePosition,
346 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
347 self.with_db(|db| goto_implementation::goto_implementation(db, position))
350 /// Returns the type definitions for the symbol at `position`.
351 pub fn goto_type_definition(
353 position: FilePosition,
354 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
355 self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
358 /// Finds all usages of the reference at point.
359 pub fn find_all_refs(
361 position: FilePosition,
362 search_scope: Option<SearchScope>,
363 ) -> Cancelable<Option<ReferenceSearchResult>> {
365 references::find_all_refs(&Semantics::new(db), position, search_scope).map(|it| it.info)
369 /// Finds all methods and free functions for the file. Does not return tests!
370 pub fn find_all_methods(&self, file_id: FileId) -> Cancelable<Vec<FileRange>> {
371 self.with_db(|db| fn_references::find_all_methods(db, file_id))
374 /// Returns a short text describing element at position.
377 position: FilePosition,
378 links_in_hover: bool,
379 ) -> Cancelable<Option<RangeInfo<HoverResult>>> {
380 self.with_db(|db| hover::hover(db, position, links_in_hover))
383 /// Computes parameter information for the given call expression.
384 pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
385 self.with_db(|db| call_info::call_info(db, position))
388 /// Computes call hierarchy candidates for the given file position.
389 pub fn call_hierarchy(
391 position: FilePosition,
392 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
393 self.with_db(|db| call_hierarchy::call_hierarchy(db, position))
396 /// Computes incoming calls for the given file position.
397 pub fn incoming_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
398 self.with_db(|db| call_hierarchy::incoming_calls(db, position))
401 /// Computes incoming calls for the given file position.
402 pub fn outgoing_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
403 self.with_db(|db| call_hierarchy::outgoing_calls(db, position))
406 /// Returns a `mod name;` declaration which created the current module.
407 pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
408 self.with_db(|db| parent_module::parent_module(db, position))
411 /// Returns crates this file belongs too.
412 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
413 self.with_db(|db| parent_module::crate_for(db, file_id))
416 /// Returns the edition of the given crate.
417 pub fn crate_edition(&self, crate_id: CrateId) -> Cancelable<Edition> {
418 self.with_db(|db| db.crate_graph()[crate_id].edition)
421 /// Returns the root file of the given crate.
422 pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
423 self.with_db(|db| db.crate_graph()[crate_id].root_file_id)
426 /// Returns the set of possible targets to run for the current file.
427 pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
428 self.with_db(|db| runnables::runnables(db, file_id))
431 /// Computes syntax highlighting for the given file
432 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HighlightedRange>> {
433 self.with_db(|db| syntax_highlighting::highlight(db, file_id, None, false))
436 /// Computes syntax highlighting for the given file range.
437 pub fn highlight_range(&self, frange: FileRange) -> Cancelable<Vec<HighlightedRange>> {
439 syntax_highlighting::highlight(db, frange.file_id, Some(frange.range), false)
443 /// Computes syntax highlighting for the given file.
444 pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancelable<String> {
445 self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
448 /// Computes completions at the given position.
451 config: &CompletionConfig,
452 position: FilePosition,
453 ) -> Cancelable<Option<Vec<CompletionItem>>> {
454 self.with_db(|db| completion::completions(db, config, position).map(Into::into))
457 /// Computes resolved assists with source changes for the given position.
458 pub fn resolved_assists(
460 config: &AssistConfig,
462 ) -> Cancelable<Vec<ResolvedAssist>> {
463 self.with_db(|db| assists::Assist::resolved(db, config, frange))
466 /// Computes unresolved assists (aka code actions aka intentions) for the given
468 pub fn unresolved_assists(
470 config: &AssistConfig,
472 ) -> Cancelable<Vec<Assist>> {
473 self.with_db(|db| Assist::unresolved(db, config, frange))
476 /// Computes the set of diagnostics for the given file.
479 config: &DiagnosticsConfig,
481 ) -> Cancelable<Vec<Diagnostic>> {
482 self.with_db(|db| diagnostics::diagnostics(db, config, file_id))
485 /// Returns the edit required to rename reference at the position to the new
489 position: FilePosition,
491 ) -> Cancelable<Option<RangeInfo<SourceChange>>> {
492 self.with_db(|db| references::rename(db, position, new_name))
495 pub fn structural_search_replace(
499 resolve_context: FilePosition,
500 selections: Vec<FileRange>,
501 ) -> Cancelable<Result<SourceChange, SsrError>> {
503 let rule: ssr::SsrRule = query.parse()?;
504 let mut match_finder = ssr::MatchFinder::in_context(db, resolve_context, selections);
505 match_finder.add_rule(rule)?;
506 let edits = if parse_only { Vec::new() } else { match_finder.edits() };
507 Ok(SourceChange::from(edits))
511 /// Performs an operation on that may be Canceled.
512 fn with_db<F, T>(&self, f: F) -> Cancelable<T>
514 F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
516 self.db.catch_canceled(f)
521 fn analysis_is_send() {
522 fn is_send<T: Send>() {}
523 is_send::<Analysis>();