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;
32 SyntaxDatabase, FilesDatabase, BaseDatabase,
33 salsa::{self, ParallelDatabase},
35 use rayon::prelude::*;
36 use relative_path::RelativePathBuf;
37 use rustc_hash::FxHashMap;
40 symbol_index::{FileSymbol, SymbolIndex},
41 db::LineIndexDatabase,
45 completion::{CompletionItem, CompletionItemKind, InsertText},
46 runnables::{Runnable, RunnableKind},
47 navigation_target::NavigationTarget,
49 pub use ra_ide_api_light::{
50 Fold, FoldKind, HighlightedRange, Severity, StructureNode,
51 LineIndex, LineCol, translate_offset_with_edit,
54 Canceled, CrateGraph, CrateId, FileId, FilePosition, FileRange, SourceRootId
57 pub type Cancelable<T> = Result<T, Canceled>;
60 pub struct AnalysisChange {
61 new_roots: Vec<(SourceRootId, bool)>,
62 roots_changed: FxHashMap<SourceRootId, RootChange>,
63 files_changed: Vec<(FileId, Arc<String>)>,
64 libraries_added: Vec<LibraryData>,
65 crate_graph: Option<CrateGraph>,
71 removed: Vec<RemoveFile>,
77 path: RelativePathBuf,
84 path: RelativePathBuf,
87 impl fmt::Debug for AnalysisChange {
88 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
89 let mut d = fmt.debug_struct("AnalysisChange");
90 if !self.new_roots.is_empty() {
91 d.field("new_roots", &self.new_roots);
93 if !self.roots_changed.is_empty() {
94 d.field("roots_changed", &self.roots_changed);
96 if !self.files_changed.is_empty() {
97 d.field("files_changed", &self.files_changed.len());
99 if !self.libraries_added.is_empty() {
100 d.field("libraries_added", &self.libraries_added.len());
102 if !self.crate_graph.is_some() {
103 d.field("crate_graph", &self.crate_graph);
109 impl fmt::Debug for RootChange {
110 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
111 fmt.debug_struct("AnalysisChange")
112 .field("added", &self.added.len())
113 .field("removed", &self.removed.len())
118 impl AnalysisChange {
119 pub fn new() -> AnalysisChange {
120 AnalysisChange::default()
123 pub fn add_root(&mut self, root_id: SourceRootId, is_local: bool) {
124 self.new_roots.push((root_id, is_local));
129 root_id: SourceRootId,
131 path: RelativePathBuf,
146 pub fn change_file(&mut self, file_id: FileId, new_text: Arc<String>) {
147 self.files_changed.push((file_id, new_text))
150 pub fn remove_file(&mut self, root_id: SourceRootId, file_id: FileId, path: RelativePathBuf) {
151 let file = RemoveFile { file_id, path };
159 pub fn add_library(&mut self, data: LibraryData) {
160 self.libraries_added.push(data)
163 pub fn set_crate_graph(&mut self, graph: CrateGraph) {
164 self.crate_graph = Some(graph);
169 pub struct SourceChange {
171 pub source_file_edits: Vec<SourceFileEdit>,
172 pub file_system_edits: Vec<FileSystemEdit>,
173 pub cursor_position: Option<FilePosition>,
177 pub struct SourceFileEdit {
183 pub enum FileSystemEdit {
185 source_root: SourceRootId,
186 path: RelativePathBuf,
190 dst_source_root: SourceRootId,
191 dst_path: RelativePathBuf,
196 pub struct Diagnostic {
198 pub range: TextRange,
199 pub fix: Option<SourceChange>,
200 pub severity: Severity,
214 pub fn new(query: String) -> Query {
215 let lowercased = query.to_lowercase();
222 limit: usize::max_value(),
226 pub fn only_types(&mut self) {
227 self.only_types = true;
230 pub fn libs(&mut self) {
234 pub fn exact(&mut self) {
238 pub fn limit(&mut self, limit: usize) {
244 pub struct RangeInfo<T> {
245 pub range: TextRange,
249 impl<T> RangeInfo<T> {
250 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
251 RangeInfo { range, info }
256 pub struct CallInfo {
258 pub doc: Option<String>,
259 pub parameters: Vec<String>,
260 pub active_parameter: Option<usize>,
263 /// `AnalysisHost` stores the current state of the world.
264 #[derive(Debug, Default)]
265 pub struct AnalysisHost {
266 db: db::RootDatabase,
270 /// Returns a snapshot of the current state, which you can query for
271 /// semantic information.
272 pub fn analysis(&self) -> Analysis {
274 db: self.db.snapshot(),
278 /// Applies changes to the current state of the world. If there are
279 /// outstanding snapshots, they will be canceled.
280 pub fn apply_change(&mut self, change: AnalysisChange) {
281 self.db.apply_change(change)
285 /// Analysis is a snapshot of a world state at a moment in time. It is the main
286 /// entry point for asking semantic information about the world. When the world
287 /// state is advanced using `AnalysisHost::apply_change` method, all existing
288 /// `Analysis` are canceled (most method return `Err(Canceled)`).
290 pub struct Analysis {
291 db: salsa::Snapshot<db::RootDatabase>,
295 /// Gets the text of the source file.
296 pub fn file_text(&self, file_id: FileId) -> Arc<String> {
297 self.db.file_text(file_id)
300 /// Gets the syntax tree of the file.
301 pub fn file_syntax(&self, file_id: FileId) -> TreeArc<SourceFile> {
302 self.db.source_file(file_id).clone()
305 /// Gets the file's `LineIndex`: data structure to convert between absolute
306 /// offsets and line/column representation.
307 pub fn file_line_index(&self, file_id: FileId) -> Arc<LineIndex> {
308 self.db.line_index(file_id)
311 /// Selects the next syntactic nodes encopasing the range.
312 pub fn extend_selection(&self, frange: FileRange) -> TextRange {
313 extend_selection::extend_selection(&self.db, frange)
316 /// Returns position of the mathcing brace (all types of braces are
318 pub fn matching_brace(&self, file: &SourceFile, offset: TextUnit) -> Option<TextUnit> {
319 ra_ide_api_light::matching_brace(file, offset)
322 /// Returns a syntax tree represented as `String`, for debug purposes.
323 // FIXME: use a better name here.
324 pub fn syntax_tree(&self, file_id: FileId) -> String {
325 let file = self.db.source_file(file_id);
326 ra_ide_api_light::syntax_tree(&file)
329 /// Returns an edit to remove all newlines in the range, cleaning up minor
330 /// stuff like trailing commas.
331 pub fn join_lines(&self, frange: FileRange) -> SourceChange {
332 let file = self.db.source_file(frange.file_id);
333 SourceChange::from_local_edit(
335 ra_ide_api_light::join_lines(&file, frange.range),
339 /// Returns an edit which should be applied when opening a new line, fixing
340 /// up minor stuff like continuing the comment.
341 pub fn on_enter(&self, position: FilePosition) -> Option<SourceChange> {
342 let file = self.db.source_file(position.file_id);
343 let edit = ra_ide_api_light::on_enter(&file, position.offset)?;
344 Some(SourceChange::from_local_edit(position.file_id, edit))
347 /// Returns an edit which should be applied after `=` was typed. Primarily,
348 /// this works when adding `let =`.
349 // FIXME: use a snippet completion instead of this hack here.
350 pub fn on_eq_typed(&self, position: FilePosition) -> Option<SourceChange> {
351 let file = self.db.source_file(position.file_id);
352 let edit = ra_ide_api_light::on_eq_typed(&file, position.offset)?;
353 Some(SourceChange::from_local_edit(position.file_id, edit))
356 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
357 pub fn on_dot_typed(&self, position: FilePosition) -> Option<SourceChange> {
358 let file = self.db.source_file(position.file_id);
359 let edit = ra_ide_api_light::on_dot_typed(&file, position.offset)?;
360 Some(SourceChange::from_local_edit(position.file_id, edit))
363 /// Returns a tree representation of symbols in the file. Useful to draw a
365 pub fn file_structure(&self, file_id: FileId) -> Vec<StructureNode> {
366 let file = self.db.source_file(file_id);
367 ra_ide_api_light::file_structure(&file)
370 /// Returns the set of folding ranges.
371 pub fn folding_ranges(&self, file_id: FileId) -> Vec<Fold> {
372 let file = self.db.source_file(file_id);
373 ra_ide_api_light::folding_ranges(&file)
376 /// Fuzzy searches for a symbol.
377 pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
379 symbol_index::world_symbols(db, query)
381 .map(NavigationTarget::from_symbol)
386 pub fn goto_definition(
388 position: FilePosition,
389 ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
391 .catch_canceled(|db| goto_definition::goto_definition(db, position))
394 /// Finds all usages of the reference at point.
395 pub fn find_all_refs(&self, position: FilePosition) -> Cancelable<Vec<(FileId, TextRange)>> {
396 self.with_db(|db| db.find_all_refs(position))
399 /// Returns a short text descrbing element at position.
400 pub fn hover(&self, position: FilePosition) -> Cancelable<Option<RangeInfo<String>>> {
401 self.with_db(|db| hover::hover(db, position))
404 /// Computes parameter information for the given call expression.
405 pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
407 .catch_canceled(|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 Ok(self.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>> {
428 .catch_canceled(|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>> {
434 .catch_canceled(|db| syntax_highlighting::highlight(db, file_id))
437 /// Computes completions at the given position.
438 pub fn completions(&self, position: FilePosition) -> Cancelable<Option<Vec<CompletionItem>>> {
439 let completions = self
441 .catch_canceled(|db| completion::completions(db, position))?;
442 Ok(completions.map(|it| it.into()))
445 /// Computes assists (aks code actons aka intentions) for the given
447 pub fn assists(&self, frange: FileRange) -> Cancelable<Vec<SourceChange>> {
448 Ok(self.db.assists(frange))
451 /// Computes the set of diagnostics for the given file.
452 pub fn diagnostics(&self, file_id: FileId) -> Cancelable<Vec<Diagnostic>> {
453 self.with_db(|db| db.diagnostics(file_id))
456 /// Computes the type of the expression at the given position.
457 pub fn type_of(&self, frange: FileRange) -> Cancelable<Option<String>> {
458 self.with_db(|db| hover::type_of(db, frange))
461 /// Returns the edit required to rename reference at the position to the new
465 position: FilePosition,
467 ) -> Cancelable<Vec<SourceFileEdit>> {
468 self.with_db(|db| db.rename(position, new_name))
471 fn with_db<F: FnOnce(&db::RootDatabase) -> T + std::panic::UnwindSafe, T>(
475 self.db.catch_canceled(f)
479 pub struct LibraryData {
480 root_id: SourceRootId,
481 root_change: RootChange,
482 symbol_index: SymbolIndex,
485 impl fmt::Debug for LibraryData {
486 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
487 f.debug_struct("LibraryData")
488 .field("root_id", &self.root_id)
489 .field("root_change", &self.root_change)
490 .field("n_symbols", &self.symbol_index.len())
497 root_id: SourceRootId,
498 files: Vec<(FileId, RelativePathBuf, Arc<String>)>,
500 let symbol_index = SymbolIndex::for_files(files.par_iter().map(|(file_id, _, text)| {
501 let file = SourceFile::parse(text);
504 let mut root_change = RootChange::default();
505 root_change.added = files
507 .map(|(file_id, path, text)| AddFile {
522 fn analysis_is_send() {
523 fn is_send<T: Send>() {}
524 is_send::<Analysis>();