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;
25 mod syntax_highlighting;
32 use std::{fmt, sync::Arc};
34 use ra_syntax::{SourceFile, TreeArc, TextRange, TextUnit};
35 use ra_text_edit::TextEdit;
37 SyntaxDatabase, FilesDatabase, BaseDatabase,
38 salsa::{self, ParallelDatabase},
40 use rayon::prelude::*;
41 use relative_path::RelativePathBuf;
42 use rustc_hash::FxHashMap;
45 symbol_index::{FileSymbol, SymbolIndex},
46 db::LineIndexDatabase,
50 completion::{CompletionItem, CompletionItemKind, InsertTextFormat},
51 runnables::{Runnable, RunnableKind},
52 navigation_target::NavigationTarget,
54 pub use ra_ide_api_light::{
55 Fold, FoldKind, HighlightedRange, Severity, StructureNode,
56 LineIndex, LineCol, translate_offset_with_edit,
59 Canceled, CrateGraph, CrateId, FileId, FilePosition, FileRange, SourceRootId
62 pub type Cancelable<T> = Result<T, Canceled>;
65 pub struct AnalysisChange {
66 new_roots: Vec<(SourceRootId, bool)>,
67 roots_changed: FxHashMap<SourceRootId, RootChange>,
68 files_changed: Vec<(FileId, Arc<String>)>,
69 libraries_added: Vec<LibraryData>,
70 crate_graph: Option<CrateGraph>,
76 removed: Vec<RemoveFile>,
82 path: RelativePathBuf,
89 path: RelativePathBuf,
92 impl fmt::Debug for AnalysisChange {
93 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
94 let mut d = fmt.debug_struct("AnalysisChange");
95 if !self.new_roots.is_empty() {
96 d.field("new_roots", &self.new_roots);
98 if !self.roots_changed.is_empty() {
99 d.field("roots_changed", &self.roots_changed);
101 if !self.files_changed.is_empty() {
102 d.field("files_changed", &self.files_changed.len());
104 if !self.libraries_added.is_empty() {
105 d.field("libraries_added", &self.libraries_added.len());
107 if !self.crate_graph.is_some() {
108 d.field("crate_graph", &self.crate_graph);
114 impl fmt::Debug for RootChange {
115 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
116 fmt.debug_struct("AnalysisChange")
117 .field("added", &self.added.len())
118 .field("removed", &self.removed.len())
123 impl AnalysisChange {
124 pub fn new() -> AnalysisChange {
125 AnalysisChange::default()
128 pub fn add_root(&mut self, root_id: SourceRootId, is_local: bool) {
129 self.new_roots.push((root_id, is_local));
134 root_id: SourceRootId,
136 path: RelativePathBuf,
151 pub fn change_file(&mut self, file_id: FileId, new_text: Arc<String>) {
152 self.files_changed.push((file_id, new_text))
155 pub fn remove_file(&mut self, root_id: SourceRootId, file_id: FileId, path: RelativePathBuf) {
156 let file = RemoveFile { file_id, path };
164 pub fn add_library(&mut self, data: LibraryData) {
165 self.libraries_added.push(data)
168 pub fn set_crate_graph(&mut self, graph: CrateGraph) {
169 self.crate_graph = Some(graph);
174 pub struct SourceChange {
176 pub source_file_edits: Vec<SourceFileEdit>,
177 pub file_system_edits: Vec<FileSystemEdit>,
178 pub cursor_position: Option<FilePosition>,
182 pub struct SourceFileEdit {
188 pub enum FileSystemEdit {
190 source_root: SourceRootId,
191 path: RelativePathBuf,
195 dst_source_root: SourceRootId,
196 dst_path: RelativePathBuf,
201 pub struct Diagnostic {
203 pub range: TextRange,
204 pub fix: Option<SourceChange>,
205 pub severity: Severity,
219 pub fn new(query: String) -> Query {
220 let lowercased = query.to_lowercase();
227 limit: usize::max_value(),
231 pub fn only_types(&mut self) {
232 self.only_types = true;
235 pub fn libs(&mut self) {
239 pub fn exact(&mut self) {
243 pub fn limit(&mut self, limit: usize) {
249 pub struct RangeInfo<T> {
250 pub range: TextRange,
254 impl<T> RangeInfo<T> {
255 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
256 RangeInfo { range, info }
261 pub struct CallInfo {
263 pub doc: Option<String>,
264 pub parameters: Vec<String>,
265 pub active_parameter: Option<usize>,
268 /// `AnalysisHost` stores the current state of the world.
269 #[derive(Debug, Default)]
270 pub struct AnalysisHost {
271 db: db::RootDatabase,
275 /// Returns a snapshot of the current state, which you can query for
276 /// semantic information.
277 pub fn analysis(&self) -> Analysis {
279 db: self.db.snapshot(),
283 /// Applies changes to the current state of the world. If there are
284 /// outstanding snapshots, they will be canceled.
285 pub fn apply_change(&mut self, change: AnalysisChange) {
286 self.db.apply_change(change)
290 /// Analysis is a snapshot of a world state at a moment in time. It is the main
291 /// entry point for asking semantic information about the world. When the world
292 /// state is advanced using `AnalysisHost::apply_change` method, all existing
293 /// `Analysis` are canceled (most method return `Err(Canceled)`).
295 pub struct Analysis {
296 db: salsa::Snapshot<db::RootDatabase>,
300 /// Debug info about the current state of the analysis
301 pub fn status(&self) -> String {
302 status::status(&*self.db)
305 /// Gets the text of the source file.
306 pub fn file_text(&self, file_id: FileId) -> Arc<String> {
307 self.db.file_text(file_id)
310 /// Gets the syntax tree of the file.
311 pub fn parse(&self, file_id: FileId) -> TreeArc<SourceFile> {
312 self.db.source_file(file_id).clone()
315 /// Gets the file's `LineIndex`: data structure to convert between absolute
316 /// offsets and line/column representation.
317 pub fn file_line_index(&self, file_id: FileId) -> Arc<LineIndex> {
318 self.db.line_index(file_id)
321 /// Selects the next syntactic nodes encopasing the range.
322 pub fn extend_selection(&self, frange: FileRange) -> Cancelable<TextRange> {
323 self.with_db(|db| extend_selection::extend_selection(db, frange))
326 /// Returns position of the mathcing brace (all types of braces are
328 pub fn matching_brace(&self, position: FilePosition) -> Option<TextUnit> {
329 let file = self.db.source_file(position.file_id);
330 ra_ide_api_light::matching_brace(&file, position.offset)
333 /// Returns a syntax tree represented as `String`, for debug purposes.
334 // FIXME: use a better name here.
335 pub fn syntax_tree(&self, file_id: FileId) -> String {
336 let file = self.db.source_file(file_id);
337 ra_ide_api_light::syntax_tree(&file)
340 /// Returns an edit to remove all newlines in the range, cleaning up minor
341 /// stuff like trailing commas.
342 pub fn join_lines(&self, frange: FileRange) -> SourceChange {
343 let file = self.db.source_file(frange.file_id);
344 SourceChange::from_local_edit(
346 ra_ide_api_light::join_lines(&file, frange.range),
350 /// Returns an edit which should be applied when opening a new line, fixing
351 /// up minor stuff like continuing the comment.
352 pub fn on_enter(&self, position: FilePosition) -> Option<SourceChange> {
353 let file = self.db.source_file(position.file_id);
354 let edit = ra_ide_api_light::on_enter(&file, position.offset)?;
355 Some(SourceChange::from_local_edit(position.file_id, edit))
358 /// Returns an edit which should be applied after `=` was typed. Primarily,
359 /// this works when adding `let =`.
360 // FIXME: use a snippet completion instead of this hack here.
361 pub fn on_eq_typed(&self, position: FilePosition) -> Option<SourceChange> {
362 let file = self.db.source_file(position.file_id);
363 let edit = ra_ide_api_light::on_eq_typed(&file, position.offset)?;
364 Some(SourceChange::from_local_edit(position.file_id, edit))
367 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
368 pub fn on_dot_typed(&self, position: FilePosition) -> Option<SourceChange> {
369 let file = self.db.source_file(position.file_id);
370 let edit = ra_ide_api_light::on_dot_typed(&file, position.offset)?;
371 Some(SourceChange::from_local_edit(position.file_id, edit))
374 /// Returns a tree representation of symbols in the file. Useful to draw a
376 pub fn file_structure(&self, file_id: FileId) -> Vec<StructureNode> {
377 let file = self.db.source_file(file_id);
378 ra_ide_api_light::file_structure(&file)
381 /// Returns the set of folding ranges.
382 pub fn folding_ranges(&self, file_id: FileId) -> Vec<Fold> {
383 let file = self.db.source_file(file_id);
384 ra_ide_api_light::folding_ranges(&file)
387 /// Fuzzy searches for a symbol.
388 pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
390 symbol_index::world_symbols(db, query)
392 .map(NavigationTarget::from_symbol)
397 pub fn goto_definition(
399 position: FilePosition,
400 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
401 self.with_db(|db| goto_definition::goto_definition(db, position))
404 /// Finds all usages of the reference at point.
405 pub fn find_all_refs(&self, position: FilePosition) -> Cancelable<Vec<(FileId, TextRange)>> {
406 self.with_db(|db| db.find_all_refs(position))
409 /// Returns a short text descrbing element at position.
410 pub fn hover(&self, position: FilePosition) -> Cancelable<Option<RangeInfo<String>>> {
411 self.with_db(|db| hover::hover(db, position))
414 /// Computes parameter information for the given call expression.
415 pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
416 self.with_db(|db| call_info::call_info(db, position))
419 /// Returns a `mod name;` declaration which created the current module.
420 pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
421 self.with_db(|db| parent_module::parent_module(db, position))
424 /// Returns crates this file belongs too.
425 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
426 self.with_db(|db| db.crate_for(file_id))
429 /// Returns the root file of the given crate.
430 pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
431 self.with_db(|db| db.crate_graph().crate_root(crate_id))
434 /// Returns the set of possible targets to run for the current file.
435 pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
436 self.with_db(|db| runnables::runnables(db, file_id))
439 /// Computes syntax highlighting for the given file.
440 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HighlightedRange>> {
441 self.with_db(|db| syntax_highlighting::highlight(db, file_id))
444 /// Computes completions at the given position.
445 pub fn completions(&self, position: FilePosition) -> Cancelable<Option<Vec<CompletionItem>>> {
446 self.with_db(|db| completion::completions(db, position).map(Into::into))
449 /// Computes assists (aks code actons aka intentions) for the given
451 pub fn assists(&self, frange: FileRange) -> Cancelable<Vec<SourceChange>> {
452 self.with_db(|db| db.assists(frange))
455 /// Computes the set of diagnostics for the given file.
456 pub fn diagnostics(&self, file_id: FileId) -> Cancelable<Vec<Diagnostic>> {
457 self.with_db(|db| db.diagnostics(file_id))
460 /// Computes the type of the expression at the given position.
461 pub fn type_of(&self, frange: FileRange) -> Cancelable<Option<String>> {
462 self.with_db(|db| hover::type_of(db, frange))
465 /// Returns the edit required to rename reference at the position to the new
469 position: FilePosition,
471 ) -> Cancelable<Option<SourceChange>> {
472 self.with_db(|db| rename::rename(db, position, new_name))
475 fn with_db<F: FnOnce(&db::RootDatabase) -> T + std::panic::UnwindSafe, T>(
479 self.db.catch_canceled(f)
483 pub struct LibraryData {
484 root_id: SourceRootId,
485 root_change: RootChange,
486 symbol_index: SymbolIndex,
489 impl fmt::Debug for LibraryData {
490 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
491 f.debug_struct("LibraryData")
492 .field("root_id", &self.root_id)
493 .field("root_change", &self.root_change)
494 .field("n_symbols", &self.symbol_index.len())
501 root_id: SourceRootId,
502 files: Vec<(FileId, RelativePathBuf, Arc<String>)>,
504 let symbol_index = SymbolIndex::for_files(files.par_iter().map(|(file_id, _, text)| {
505 let file = SourceFile::parse(text);
508 let mut root_change = RootChange::default();
509 root_change.added = files
511 .map(|(file_id, path, text)| AddFile {
526 fn analysis_is_send() {
527 fn is_send<T: Send>() {}
528 is_send::<Analysis>();