1 //! ra_ide_api 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 `ra_hir` crate, where majority of the analysis happens.
7 //! However, IDE specific bits of the analysis (most notably completion) happen
10 //! The sibling `ra_ide_api_light` handles thouse bits of IDE functionality
11 //! which are restricted to a single file and need only syntax.
14 pub mod mock_analysis;
16 mod navigation_target;
24 mod syntax_highlighting;
28 use std::{fmt, sync::Arc};
30 use ra_syntax::{SourceFile, TreeArc, TextRange, TextUnit};
31 use ra_text_edit::TextEdit;
33 SyntaxDatabase, FilesDatabase, BaseDatabase,
34 salsa::{self, ParallelDatabase},
36 use rayon::prelude::*;
37 use relative_path::RelativePathBuf;
38 use rustc_hash::FxHashMap;
41 symbol_index::{FileSymbol, SymbolIndex},
42 db::LineIndexDatabase,
46 completion::{CompletionItem, CompletionItemKind, InsertTextFormat},
47 runnables::{Runnable, RunnableKind},
48 navigation_target::NavigationTarget,
50 pub use ra_ide_api_light::{
51 Fold, FoldKind, HighlightedRange, Severity, StructureNode,
52 LineIndex, LineCol, translate_offset_with_edit,
55 Canceled, CrateGraph, CrateId, FileId, FilePosition, FileRange, SourceRootId
58 pub type Cancelable<T> = Result<T, Canceled>;
61 pub struct AnalysisChange {
62 new_roots: Vec<(SourceRootId, bool)>,
63 roots_changed: FxHashMap<SourceRootId, RootChange>,
64 files_changed: Vec<(FileId, Arc<String>)>,
65 libraries_added: Vec<LibraryData>,
66 crate_graph: Option<CrateGraph>,
72 removed: Vec<RemoveFile>,
78 path: RelativePathBuf,
85 path: RelativePathBuf,
88 impl fmt::Debug for AnalysisChange {
89 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
90 let mut d = fmt.debug_struct("AnalysisChange");
91 if !self.new_roots.is_empty() {
92 d.field("new_roots", &self.new_roots);
94 if !self.roots_changed.is_empty() {
95 d.field("roots_changed", &self.roots_changed);
97 if !self.files_changed.is_empty() {
98 d.field("files_changed", &self.files_changed.len());
100 if !self.libraries_added.is_empty() {
101 d.field("libraries_added", &self.libraries_added.len());
103 if !self.crate_graph.is_some() {
104 d.field("crate_graph", &self.crate_graph);
110 impl fmt::Debug for RootChange {
111 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
112 fmt.debug_struct("AnalysisChange")
113 .field("added", &self.added.len())
114 .field("removed", &self.removed.len())
119 impl AnalysisChange {
120 pub fn new() -> AnalysisChange {
121 AnalysisChange::default()
124 pub fn add_root(&mut self, root_id: SourceRootId, is_local: bool) {
125 self.new_roots.push((root_id, is_local));
130 root_id: SourceRootId,
132 path: RelativePathBuf,
147 pub fn change_file(&mut self, file_id: FileId, new_text: Arc<String>) {
148 self.files_changed.push((file_id, new_text))
151 pub fn remove_file(&mut self, root_id: SourceRootId, file_id: FileId, path: RelativePathBuf) {
152 let file = RemoveFile { file_id, path };
160 pub fn add_library(&mut self, data: LibraryData) {
161 self.libraries_added.push(data)
164 pub fn set_crate_graph(&mut self, graph: CrateGraph) {
165 self.crate_graph = Some(graph);
170 pub struct SourceChange {
172 pub source_file_edits: Vec<SourceFileEdit>,
173 pub file_system_edits: Vec<FileSystemEdit>,
174 pub cursor_position: Option<FilePosition>,
178 pub struct SourceFileEdit {
184 pub enum FileSystemEdit {
186 source_root: SourceRootId,
187 path: RelativePathBuf,
191 dst_source_root: SourceRootId,
192 dst_path: RelativePathBuf,
197 pub struct Diagnostic {
199 pub range: TextRange,
200 pub fix: Option<SourceChange>,
201 pub severity: Severity,
215 pub fn new(query: String) -> Query {
216 let lowercased = query.to_lowercase();
223 limit: usize::max_value(),
227 pub fn only_types(&mut self) {
228 self.only_types = true;
231 pub fn libs(&mut self) {
235 pub fn exact(&mut self) {
239 pub fn limit(&mut self, limit: usize) {
245 pub struct RangeInfo<T> {
246 pub range: TextRange,
250 impl<T> RangeInfo<T> {
251 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
252 RangeInfo { range, info }
257 pub struct CallInfo {
259 pub doc: Option<String>,
260 pub parameters: Vec<String>,
261 pub active_parameter: Option<usize>,
264 /// `AnalysisHost` stores the current state of the world.
265 #[derive(Debug, Default)]
266 pub struct AnalysisHost {
267 db: db::RootDatabase,
271 /// Returns a snapshot of the current state, which you can query for
272 /// semantic information.
273 pub fn analysis(&self) -> Analysis {
275 db: self.db.snapshot(),
279 /// Applies changes to the current state of the world. If there are
280 /// outstanding snapshots, they will be canceled.
281 pub fn apply_change(&mut self, change: AnalysisChange) {
282 self.db.apply_change(change)
286 /// Analysis is a snapshot of a world state at a moment in time. It is the main
287 /// entry point for asking semantic information about the world. When the world
288 /// state is advanced using `AnalysisHost::apply_change` method, all existing
289 /// `Analysis` are canceled (most method return `Err(Canceled)`).
291 pub struct Analysis {
292 db: salsa::Snapshot<db::RootDatabase>,
296 /// Gets the text of the source file.
297 pub fn file_text(&self, file_id: FileId) -> Arc<String> {
298 self.db.file_text(file_id)
301 /// Gets the syntax tree of the file.
302 pub fn parse(&self, file_id: FileId) -> TreeArc<SourceFile> {
303 self.db.source_file(file_id).clone()
306 /// Gets the file's `LineIndex`: data structure to convert between absolute
307 /// offsets and line/column representation.
308 pub fn file_line_index(&self, file_id: FileId) -> Arc<LineIndex> {
309 self.db.line_index(file_id)
312 /// Selects the next syntactic nodes encopasing the range.
313 pub fn extend_selection(&self, frange: FileRange) -> Cancelable<TextRange> {
314 self.with_db(|db| extend_selection::extend_selection(db, frange))
317 /// Returns position of the mathcing brace (all types of braces are
319 pub fn matching_brace(&self, position: FilePosition) -> Option<TextUnit> {
320 let file = self.db.source_file(position.file_id);
321 ra_ide_api_light::matching_brace(&file, position.offset)
324 /// Returns a syntax tree represented as `String`, for debug purposes.
325 // FIXME: use a better name here.
326 pub fn syntax_tree(&self, file_id: FileId) -> String {
327 let file = self.db.source_file(file_id);
328 ra_ide_api_light::syntax_tree(&file)
331 /// Returns an edit to remove all newlines in the range, cleaning up minor
332 /// stuff like trailing commas.
333 pub fn join_lines(&self, frange: FileRange) -> SourceChange {
334 let file = self.db.source_file(frange.file_id);
335 SourceChange::from_local_edit(
337 ra_ide_api_light::join_lines(&file, frange.range),
341 /// Returns an edit which should be applied when opening a new line, fixing
342 /// up minor stuff like continuing the comment.
343 pub fn on_enter(&self, position: FilePosition) -> Option<SourceChange> {
344 let file = self.db.source_file(position.file_id);
345 let edit = ra_ide_api_light::on_enter(&file, position.offset)?;
346 Some(SourceChange::from_local_edit(position.file_id, edit))
349 /// Returns an edit which should be applied after `=` was typed. Primarily,
350 /// this works when adding `let =`.
351 // FIXME: use a snippet completion instead of this hack here.
352 pub fn on_eq_typed(&self, position: FilePosition) -> Option<SourceChange> {
353 let file = self.db.source_file(position.file_id);
354 let edit = ra_ide_api_light::on_eq_typed(&file, position.offset)?;
355 Some(SourceChange::from_local_edit(position.file_id, edit))
358 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
359 pub fn on_dot_typed(&self, position: FilePosition) -> Option<SourceChange> {
360 let file = self.db.source_file(position.file_id);
361 let edit = ra_ide_api_light::on_dot_typed(&file, position.offset)?;
362 Some(SourceChange::from_local_edit(position.file_id, edit))
365 /// Returns a tree representation of symbols in the file. Useful to draw a
367 pub fn file_structure(&self, file_id: FileId) -> Vec<StructureNode> {
368 let file = self.db.source_file(file_id);
369 ra_ide_api_light::file_structure(&file)
372 /// Returns the set of folding ranges.
373 pub fn folding_ranges(&self, file_id: FileId) -> Vec<Fold> {
374 let file = self.db.source_file(file_id);
375 ra_ide_api_light::folding_ranges(&file)
378 /// Fuzzy searches for a symbol.
379 pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
381 symbol_index::world_symbols(db, query)
383 .map(NavigationTarget::from_symbol)
388 pub fn goto_definition(
390 position: FilePosition,
391 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
392 self.with_db(|db| goto_definition::goto_definition(db, position))
395 /// Finds all usages of the reference at point.
396 pub fn find_all_refs(&self, position: FilePosition) -> Cancelable<Vec<(FileId, TextRange)>> {
397 self.with_db(|db| db.find_all_refs(position))
400 /// Returns a short text descrbing element at position.
401 pub fn hover(&self, position: FilePosition) -> Cancelable<Option<RangeInfo<String>>> {
402 self.with_db(|db| hover::hover(db, position))
405 /// Computes parameter information for the given call expression.
406 pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
407 self.with_db(|db| call_info::call_info(db, position))
410 /// Returns a `mod name;` declaration which created the current module.
411 pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
412 self.with_db(|db| parent_module::parent_module(db, position))
415 /// Returns crates this file belongs too.
416 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
417 self.with_db(|db| db.crate_for(file_id))
420 /// Returns the root file of the given crate.
421 pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
422 self.with_db(|db| db.crate_graph().crate_root(crate_id))
425 /// Returns the set of possible targets to run for the current file.
426 pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
427 self.with_db(|db| runnables::runnables(db, file_id))
430 /// Computes syntax highlighting for the given file.
431 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HighlightedRange>> {
432 self.with_db(|db| syntax_highlighting::highlight(db, file_id))
435 /// Computes completions at the given position.
436 pub fn completions(&self, position: FilePosition) -> Cancelable<Option<Vec<CompletionItem>>> {
437 self.with_db(|db| completion::completions(db, position).map(Into::into))
440 /// Computes assists (aks code actons aka intentions) for the given
442 pub fn assists(&self, frange: FileRange) -> Cancelable<Vec<SourceChange>> {
443 self.with_db(|db| db.assists(frange))
446 /// Computes the set of diagnostics for the given file.
447 pub fn diagnostics(&self, file_id: FileId) -> Cancelable<Vec<Diagnostic>> {
448 self.with_db(|db| db.diagnostics(file_id))
451 /// Computes the type of the expression at the given position.
452 pub fn type_of(&self, frange: FileRange) -> Cancelable<Option<String>> {
453 self.with_db(|db| hover::type_of(db, frange))
456 /// Returns the edit required to rename reference at the position to the new
460 position: FilePosition,
462 ) -> Cancelable<Option<SourceChange>> {
463 self.with_db(|db| rename::rename(db, position, new_name))
466 fn with_db<F: FnOnce(&db::RootDatabase) -> T + std::panic::UnwindSafe, T>(
470 self.db.catch_canceled(f)
474 pub struct LibraryData {
475 root_id: SourceRootId,
476 root_change: RootChange,
477 symbol_index: SymbolIndex,
480 impl fmt::Debug for LibraryData {
481 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
482 f.debug_struct("LibraryData")
483 .field("root_id", &self.root_id)
484 .field("root_change", &self.root_change)
485 .field("n_symbols", &self.symbol_index.len())
492 root_id: SourceRootId,
493 files: Vec<(FileId, RelativePathBuf, Arc<String>)>,
495 let symbol_index = SymbolIndex::for_files(files.par_iter().map(|(file_id, _, text)| {
496 let file = SourceFile::parse(text);
499 let mut root_change = RootChange::default();
500 root_change.added = files
502 .map(|(file_id, path, text)| AddFile {
517 fn analysis_is_send() {
518 fn is_send<T: Send>() {}
519 is_send::<Analysis>();