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;
27 use std::{fmt, sync::Arc};
29 use ra_syntax::{SourceFile, TreeArc, TextRange, TextUnit};
30 use ra_text_edit::TextEdit;
31 use ra_db::{SyntaxDatabase, FilesDatabase, BaseDatabase};
32 use rayon::prelude::*;
33 use relative_path::RelativePathBuf;
34 use rustc_hash::FxHashMap;
35 use salsa::ParallelDatabase;
38 symbol_index::{FileSymbol, SymbolIndex},
39 db::LineIndexDatabase,
43 completion::{CompletionItem, CompletionItemKind, InsertText},
44 runnables::{Runnable, RunnableKind},
45 navigation_target::NavigationTarget,
47 pub use ra_ide_api_light::{
48 Fold, FoldKind, HighlightedRange, Severity, StructureNode,
49 LineIndex, LineCol, translate_offset_with_edit,
52 Canceled, CrateGraph, CrateId, FileId, FilePosition, FileRange, SourceRootId
55 pub type Cancelable<T> = Result<T, Canceled>;
58 pub struct AnalysisChange {
59 new_roots: Vec<(SourceRootId, bool)>,
60 roots_changed: FxHashMap<SourceRootId, RootChange>,
61 files_changed: Vec<(FileId, Arc<String>)>,
62 libraries_added: Vec<LibraryData>,
63 crate_graph: Option<CrateGraph>,
69 removed: Vec<RemoveFile>,
75 path: RelativePathBuf,
82 path: RelativePathBuf,
85 impl fmt::Debug for AnalysisChange {
86 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
87 let mut d = fmt.debug_struct("AnalysisChange");
88 if !self.new_roots.is_empty() {
89 d.field("new_roots", &self.new_roots);
91 if !self.roots_changed.is_empty() {
92 d.field("roots_changed", &self.roots_changed);
94 if !self.files_changed.is_empty() {
95 d.field("files_changed", &self.files_changed.len());
97 if !self.libraries_added.is_empty() {
98 d.field("libraries_added", &self.libraries_added.len());
100 if !self.crate_graph.is_some() {
101 d.field("crate_graph", &self.crate_graph);
107 impl fmt::Debug for RootChange {
108 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
109 fmt.debug_struct("AnalysisChange")
110 .field("added", &self.added.len())
111 .field("removed", &self.removed.len())
116 impl AnalysisChange {
117 pub fn new() -> AnalysisChange {
118 AnalysisChange::default()
121 pub fn add_root(&mut self, root_id: SourceRootId, is_local: bool) {
122 self.new_roots.push((root_id, is_local));
127 root_id: SourceRootId,
129 path: RelativePathBuf,
144 pub fn change_file(&mut self, file_id: FileId, new_text: Arc<String>) {
145 self.files_changed.push((file_id, new_text))
148 pub fn remove_file(&mut self, root_id: SourceRootId, file_id: FileId, path: RelativePathBuf) {
149 let file = RemoveFile { file_id, path };
157 pub fn add_library(&mut self, data: LibraryData) {
158 self.libraries_added.push(data)
161 pub fn set_crate_graph(&mut self, graph: CrateGraph) {
162 self.crate_graph = Some(graph);
167 pub struct SourceChange {
169 pub source_file_edits: Vec<SourceFileEdit>,
170 pub file_system_edits: Vec<FileSystemEdit>,
171 pub cursor_position: Option<FilePosition>,
175 pub struct SourceFileEdit {
181 pub enum FileSystemEdit {
183 source_root: SourceRootId,
184 path: RelativePathBuf,
188 dst_source_root: SourceRootId,
189 dst_path: RelativePathBuf,
194 pub struct Diagnostic {
196 pub range: TextRange,
197 pub fix: Option<SourceChange>,
198 pub severity: Severity,
212 pub fn new(query: String) -> Query {
213 let lowercased = query.to_lowercase();
220 limit: usize::max_value(),
224 pub fn only_types(&mut self) {
225 self.only_types = true;
228 pub fn libs(&mut self) {
232 pub fn exact(&mut self) {
236 pub fn limit(&mut self, limit: usize) {
242 pub struct RangeInfo<T> {
243 pub range: TextRange,
247 impl<T> RangeInfo<T> {
248 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
249 RangeInfo { range, info }
254 pub struct CallInfo {
256 pub doc: Option<String>,
257 pub parameters: Vec<String>,
258 pub active_parameter: Option<usize>,
261 /// `AnalysisHost` stores the current state of the world.
262 #[derive(Debug, Default)]
263 pub struct AnalysisHost {
264 db: db::RootDatabase,
268 /// Returns a snapshot of the current state, which you can query for
269 /// semantic information.
270 pub fn analysis(&self) -> Analysis {
272 db: self.db.snapshot(),
276 /// Applies changes to the current state of the world. If there are
277 /// outstanding snapshots, they will be canceled.
278 pub fn apply_change(&mut self, change: AnalysisChange) {
279 self.db.apply_change(change)
283 /// Analysis is a snapshot of a world state at a moment in time. It is the main
284 /// entry point for asking semantic information about the world. When the world
285 /// state is advanced using `AnalysisHost::apply_change` method, all existing
286 /// `Analysis` are canceled (most method return `Err(Canceled)`).
288 pub struct Analysis {
289 db: salsa::Snapshot<db::RootDatabase>,
293 /// Gets the text of the source file.
294 pub fn file_text(&self, file_id: FileId) -> Arc<String> {
295 self.db.file_text(file_id)
298 /// Gets the syntax tree of the file.
299 pub fn file_syntax(&self, file_id: FileId) -> TreeArc<SourceFile> {
300 self.db.source_file(file_id).clone()
303 /// Gets the file's `LineIndex`: data structure to convert between absolute
304 /// offsets and line/column representation.
305 pub fn file_line_index(&self, file_id: FileId) -> Arc<LineIndex> {
306 self.db.line_index(file_id)
309 /// Selects the next syntactic nodes encopasing the range.
310 pub fn extend_selection(&self, frange: FileRange) -> TextRange {
311 extend_selection::extend_selection(&self.db, frange)
314 /// Returns position of the mathcing brace (all types of braces are
316 pub fn matching_brace(&self, file: &SourceFile, offset: TextUnit) -> Option<TextUnit> {
317 ra_ide_api_light::matching_brace(file, offset)
320 /// Returns a syntax tree represented as `String`, for debug purposes.
321 // FIXME: use a better name here.
322 pub fn syntax_tree(&self, file_id: FileId) -> String {
323 let file = self.db.source_file(file_id);
324 ra_ide_api_light::syntax_tree(&file)
327 /// Returns an edit to remove all newlines in the range, cleaning up minor
328 /// stuff like trailing commas.
329 pub fn join_lines(&self, frange: FileRange) -> SourceChange {
330 let file = self.db.source_file(frange.file_id);
331 SourceChange::from_local_edit(
333 ra_ide_api_light::join_lines(&file, frange.range),
337 /// Returns an edit which should be applied when opening a new line, fixing
338 /// up minor stuff like continuing the comment.
339 pub fn on_enter(&self, position: FilePosition) -> Option<SourceChange> {
340 let file = self.db.source_file(position.file_id);
341 let edit = ra_ide_api_light::on_enter(&file, position.offset)?;
342 Some(SourceChange::from_local_edit(position.file_id, edit))
345 /// Returns an edit which should be applied after `=` was typed. Primarily,
346 /// this works when adding `let =`.
347 // FIXME: use a snippet completion instead of this hack here.
348 pub fn on_eq_typed(&self, position: FilePosition) -> Option<SourceChange> {
349 let file = self.db.source_file(position.file_id);
350 let edit = ra_ide_api_light::on_eq_typed(&file, position.offset)?;
351 Some(SourceChange::from_local_edit(position.file_id, edit))
354 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
355 pub fn on_dot_typed(&self, position: FilePosition) -> Option<SourceChange> {
356 let file = self.db.source_file(position.file_id);
357 let edit = ra_ide_api_light::on_dot_typed(&file, position.offset)?;
358 Some(SourceChange::from_local_edit(position.file_id, edit))
361 /// Returns a tree representation of symbols in the file. Useful to draw a
363 pub fn file_structure(&self, file_id: FileId) -> Vec<StructureNode> {
364 let file = self.db.source_file(file_id);
365 ra_ide_api_light::file_structure(&file)
368 /// Returns the set of folding ranges.
369 pub fn folding_ranges(&self, file_id: FileId) -> Vec<Fold> {
370 let file = self.db.source_file(file_id);
371 ra_ide_api_light::folding_ranges(&file)
374 /// Fuzzy searches for a symbol.
375 pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
377 symbol_index::world_symbols(db, query)
379 .map(NavigationTarget::from_symbol)
384 pub fn goto_definition(
386 position: FilePosition,
387 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
389 .catch_canceled(|db| goto_definition::goto_definition(db, position))
392 /// Finds all usages of the reference at point.
393 pub fn find_all_refs(&self, position: FilePosition) -> Cancelable<Vec<(FileId, TextRange)>> {
394 self.with_db(|db| db.find_all_refs(position))
397 /// Returns a short text descrbing element at position.
398 pub fn hover(&self, position: FilePosition) -> Cancelable<Option<RangeInfo<String>>> {
399 self.with_db(|db| hover::hover(db, position))
402 /// Computes parameter information for the given call expression.
403 pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
405 .catch_canceled(|db| call_info::call_info(db, position))
408 /// Returns a `mod name;` declaration which created the current module.
409 pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
410 self.with_db(|db| parent_module::parent_module(db, position))
413 /// Returns crates this file belongs too.
414 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
415 self.with_db(|db| db.crate_for(file_id))
418 /// Returns the root file of the given crate.
419 pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
420 Ok(self.db.crate_graph().crate_root(crate_id))
423 /// Returns the set of possible targets to run for the current file.
424 pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
426 .catch_canceled(|db| runnables::runnables(db, file_id))
429 /// Computes syntax highlighting for the given file.
430 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HighlightedRange>> {
432 .catch_canceled(|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 let completions = self
439 .catch_canceled(|db| completion::completions(db, position))?;
440 Ok(completions.map(|it| it.into()))
443 /// Computes assists (aks code actons aka intentions) for the given
445 pub fn assists(&self, frange: FileRange) -> Cancelable<Vec<SourceChange>> {
446 Ok(self.db.assists(frange))
449 /// Computes the set of diagnostics for the given file.
450 pub fn diagnostics(&self, file_id: FileId) -> Cancelable<Vec<Diagnostic>> {
451 self.with_db(|db| db.diagnostics(file_id))?
454 /// Computes the type of the expression at the given position.
455 pub fn type_of(&self, frange: FileRange) -> Cancelable<Option<String>> {
456 self.with_db(|db| hover::type_of(db, frange))
459 /// Returns the edit required to rename reference at the position to the new
463 position: FilePosition,
465 ) -> Cancelable<Vec<SourceFileEdit>> {
466 self.with_db(|db| db.rename(position, new_name))
469 fn with_db<F: FnOnce(&db::RootDatabase) -> T + std::panic::UnwindSafe, T>(
473 self.db.catch_canceled(f)
477 pub struct LibraryData {
478 root_id: SourceRootId,
479 root_change: RootChange,
480 symbol_index: SymbolIndex,
483 impl fmt::Debug for LibraryData {
484 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
485 f.debug_struct("LibraryData")
486 .field("root_id", &self.root_id)
487 .field("root_change", &self.root_change)
488 .field("n_symbols", &self.symbol_index.len())
495 root_id: SourceRootId,
496 files: Vec<(FileId, RelativePathBuf, Arc<String>)>,
498 let symbol_index = SymbolIndex::for_files(files.par_iter().map(|(file_id, _, text)| {
499 let file = SourceFile::parse(text);
502 let mut root_change = RootChange::default();
503 root_change.added = files
505 .map(|(file_id, path, text)| AddFile {
520 fn analysis_is_send() {
521 fn is_send<T: Send>() {}
522 is_send::<Analysis>();