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.
15 None => return Ok(None),
25 pub mod mock_analysis;
32 mod syntax_highlighting;
34 use std::{fmt, sync::Arc};
36 use ra_syntax::{SmolStr, SourceFile, TreePtr, SyntaxKind, TextRange, TextUnit};
37 use ra_text_edit::TextEdit;
38 use ra_db::{SyntaxDatabase, FilesDatabase, LocalSyntaxPtr, BaseDatabase};
39 use rayon::prelude::*;
40 use relative_path::RelativePathBuf;
41 use rustc_hash::FxHashMap;
42 use salsa::ParallelDatabase;
45 symbol_index::{FileSymbol, SymbolIndex},
46 db::LineIndexDatabase,
50 completion::{CompletionItem, CompletionItemKind, InsertText},
51 runnables::{Runnable, RunnableKind},
53 pub use ra_ide_api_light::{
54 Fold, FoldKind, HighlightedRange, Severity, StructureNode,
55 LineIndex, LineCol, translate_offset_with_edit,
58 Cancelable, Canceled, CrateGraph, CrateId, FileId, FilePosition, FileRange, SourceRootId
62 pub struct AnalysisChange {
63 new_roots: Vec<(SourceRootId, bool)>,
64 roots_changed: FxHashMap<SourceRootId, RootChange>,
65 files_changed: Vec<(FileId, Arc<String>)>,
66 libraries_added: Vec<LibraryData>,
67 crate_graph: Option<CrateGraph>,
73 removed: Vec<RemoveFile>,
79 path: RelativePathBuf,
86 path: RelativePathBuf,
89 impl fmt::Debug for AnalysisChange {
90 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
91 let mut d = fmt.debug_struct("AnalysisChange");
92 if !self.new_roots.is_empty() {
93 d.field("new_roots", &self.new_roots);
95 if !self.roots_changed.is_empty() {
96 d.field("roots_changed", &self.roots_changed);
98 if !self.files_changed.is_empty() {
99 d.field("files_changed", &self.files_changed.len());
101 if !self.libraries_added.is_empty() {
102 d.field("libraries_added", &self.libraries_added.len());
104 if !self.crate_graph.is_some() {
105 d.field("crate_graph", &self.crate_graph);
111 impl fmt::Debug for RootChange {
112 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
113 fmt.debug_struct("AnalysisChange")
114 .field("added", &self.added.len())
115 .field("removed", &self.removed.len())
120 impl AnalysisChange {
121 pub fn new() -> AnalysisChange {
122 AnalysisChange::default()
125 pub fn add_root(&mut self, root_id: SourceRootId, is_local: bool) {
126 self.new_roots.push((root_id, is_local));
131 root_id: SourceRootId,
133 path: RelativePathBuf,
148 pub fn change_file(&mut self, file_id: FileId, new_text: Arc<String>) {
149 self.files_changed.push((file_id, new_text))
152 pub fn remove_file(&mut self, root_id: SourceRootId, file_id: FileId, path: RelativePathBuf) {
153 let file = RemoveFile { file_id, path };
161 pub fn add_library(&mut self, data: LibraryData) {
162 self.libraries_added.push(data)
165 pub fn set_crate_graph(&mut self, graph: CrateGraph) {
166 self.crate_graph = Some(graph);
171 pub struct SourceChange {
173 pub source_file_edits: Vec<SourceFileEdit>,
174 pub file_system_edits: Vec<FileSystemEdit>,
175 pub cursor_position: Option<FilePosition>,
179 pub struct SourceFileEdit {
185 pub enum FileSystemEdit {
187 source_root: SourceRootId,
188 path: RelativePathBuf,
192 dst_source_root: SourceRootId,
193 dst_path: RelativePathBuf,
198 pub struct Diagnostic {
200 pub range: TextRange,
201 pub fix: Option<SourceChange>,
202 pub severity: Severity,
216 pub fn new(query: String) -> Query {
217 let lowercased = query.to_lowercase();
224 limit: usize::max_value(),
228 pub fn only_types(&mut self) {
229 self.only_types = true;
232 pub fn libs(&mut self) {
236 pub fn exact(&mut self) {
240 pub fn limit(&mut self, limit: usize) {
245 /// `NavigationTarget` represents and element in the editor's UI whihc you can
246 /// click on to navigate to a particular piece of code.
248 /// Typically, a `NavigationTarget` corresponds to some element in the source
249 /// code, like a function or a struct, but this is not strictly required.
250 #[derive(Debug, Clone)]
251 pub struct NavigationTarget {
256 // Should be DefId ideally
257 ptr: Option<LocalSyntaxPtr>,
260 impl NavigationTarget {
261 fn from_symbol(symbol: FileSymbol) -> NavigationTarget {
263 file_id: symbol.file_id,
264 name: symbol.name.clone(),
265 kind: symbol.ptr.kind(),
266 range: symbol.ptr.range(),
267 ptr: Some(symbol.ptr.clone()),
271 pub fn name(&self) -> &SmolStr {
275 pub fn kind(&self) -> SyntaxKind {
279 pub fn file_id(&self) -> FileId {
283 pub fn range(&self) -> TextRange {
289 pub struct RangeInfo<T> {
290 pub range: TextRange,
294 impl<T> RangeInfo<T> {
295 fn new(range: TextRange, info: T) -> RangeInfo<T> {
296 RangeInfo { range, info }
301 pub struct CallInfo {
303 pub doc: Option<String>,
304 pub parameters: Vec<String>,
305 pub active_parameter: Option<usize>,
308 /// `AnalysisHost` stores the current state of the world.
309 #[derive(Debug, Default)]
310 pub struct AnalysisHost {
311 db: db::RootDatabase,
315 /// Returns a snapshot of the current state, which you can query for
316 /// semantic information.
317 pub fn analysis(&self) -> Analysis {
319 db: self.db.snapshot(),
323 /// Applies changes to the current state of the world. If there are
324 /// outstanding snapshots, they will be canceled.
325 pub fn apply_change(&mut self, change: AnalysisChange) {
326 self.db.apply_change(change)
330 /// Analysis is a snapshot of a world state at a moment in time. It is the main
331 /// entry point for asking semantic information about the world. When the world
332 /// state is advanced using `AnalysisHost::apply_change` method, all existing
333 /// `Analysis` are canceled (most method return `Err(Canceled)`).
335 pub struct Analysis {
336 db: salsa::Snapshot<db::RootDatabase>,
340 /// Gets the text of the source file.
341 pub fn file_text(&self, file_id: FileId) -> Arc<String> {
342 self.db.file_text(file_id)
345 /// Gets the syntax tree of the file.
346 pub fn file_syntax(&self, file_id: FileId) -> TreePtr<SourceFile> {
347 self.db.source_file(file_id).clone()
350 /// Gets the file's `LineIndex`: data structure to convert between absolute
351 /// offsets and line/column representation.
352 pub fn file_line_index(&self, file_id: FileId) -> Arc<LineIndex> {
353 self.db.line_index(file_id)
356 /// Selects the next syntactic nodes encopasing the range.
357 pub fn extend_selection(&self, frange: FileRange) -> TextRange {
358 extend_selection::extend_selection(&self.db, frange)
361 /// Returns position of the mathcing brace (all types of braces are
363 pub fn matching_brace(&self, file: &SourceFile, offset: TextUnit) -> Option<TextUnit> {
364 ra_ide_api_light::matching_brace(file, offset)
367 /// Returns a syntax tree represented as `String`, for debug purposes.
368 // FIXME: use a better name here.
369 pub fn syntax_tree(&self, file_id: FileId) -> String {
370 let file = self.db.source_file(file_id);
371 ra_ide_api_light::syntax_tree(&file)
374 /// Returns an edit to remove all newlines in the range, cleaning up minor
375 /// stuff like trailing commas.
376 pub fn join_lines(&self, frange: FileRange) -> SourceChange {
377 let file = self.db.source_file(frange.file_id);
378 SourceChange::from_local_edit(
380 ra_ide_api_light::join_lines(&file, frange.range),
384 /// Returns an edit which should be applied when opening a new line, fixing
385 /// up minor stuff like continuing the comment.
386 pub fn on_enter(&self, position: FilePosition) -> Option<SourceChange> {
387 let file = self.db.source_file(position.file_id);
388 let edit = ra_ide_api_light::on_enter(&file, position.offset)?;
389 Some(SourceChange::from_local_edit(position.file_id, edit))
392 /// Returns an edit which should be applied after `=` was typed. Primarily,
393 /// this works when adding `let =`.
394 // FIXME: use a snippet completion instead of this hack here.
395 pub fn on_eq_typed(&self, position: FilePosition) -> Option<SourceChange> {
396 let file = self.db.source_file(position.file_id);
397 let edit = ra_ide_api_light::on_eq_typed(&file, position.offset)?;
398 Some(SourceChange::from_local_edit(position.file_id, edit))
401 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
402 pub fn on_dot_typed(&self, position: FilePosition) -> Option<SourceChange> {
403 let file = self.db.source_file(position.file_id);
404 let edit = ra_ide_api_light::on_dot_typed(&file, position.offset)?;
405 Some(SourceChange::from_local_edit(position.file_id, edit))
408 /// Returns a tree representation of symbols in the file. Useful to draw a
410 pub fn file_structure(&self, file_id: FileId) -> Vec<StructureNode> {
411 let file = self.db.source_file(file_id);
412 ra_ide_api_light::file_structure(&file)
415 /// Returns the set of folding ranges.
416 pub fn folding_ranges(&self, file_id: FileId) -> Vec<Fold> {
417 let file = self.db.source_file(file_id);
418 ra_ide_api_light::folding_ranges(&file)
421 /// Fuzzy searches for a symbol.
422 pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
424 let res = symbol_index::world_symbols(db, query)?
426 .map(NavigationTarget::from_symbol)
427 .collect::<Vec<_>>();
432 pub fn goto_definition(
434 position: FilePosition,
435 ) -> Cancelable<Option<Vec<NavigationTarget>>> {
437 .catch_canceled(|db| goto_definition::goto_definition(db, position))?
440 /// Finds all usages of the reference at point.
441 pub fn find_all_refs(&self, position: FilePosition) -> Cancelable<Vec<(FileId, TextRange)>> {
442 self.with_db(|db| db.find_all_refs(position))?
445 /// Returns a short text descrbing element at position.
446 pub fn hover(&self, position: FilePosition) -> Cancelable<Option<RangeInfo<String>>> {
447 self.with_db(|db| hover::hover(db, position))?
450 /// Computes parameter information for the given call expression.
451 pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
453 .catch_canceled(|db| call_info::call_info(db, position))?
456 /// Returns a `mod name;` declaration which created the current module.
457 pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
458 self.with_db(|db| db.parent_module(position))?
461 /// Returns crates this file belongs too.
462 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
463 self.with_db(|db| db.crate_for(file_id))?
466 /// Returns the root file of the given crate.
467 pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
468 Ok(self.db.crate_graph().crate_root(crate_id))
471 /// Returns the set of possible targets to run for the current file.
472 pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
474 .catch_canceled(|db| runnables::runnables(db, file_id))?
477 /// Computes syntax highlighting for the given file.
478 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HighlightedRange>> {
480 .catch_canceled(|db| syntax_highlighting::highlight(db, file_id))?
483 /// Computes completions at the given position.
484 pub fn completions(&self, position: FilePosition) -> Cancelable<Option<Vec<CompletionItem>>> {
485 let completions = self
487 .catch_canceled(|db| completion::completions(db, position))??;
488 Ok(completions.map(|it| it.into()))
491 /// Computes assists (aks code actons aka intentions) for the given
493 pub fn assists(&self, frange: FileRange) -> Cancelable<Vec<SourceChange>> {
494 Ok(self.db.assists(frange))
497 /// Computes the set of diagnostics for the given file.
498 pub fn diagnostics(&self, file_id: FileId) -> Cancelable<Vec<Diagnostic>> {
499 self.with_db(|db| db.diagnostics(file_id))?
502 /// Computes the type of the expression at the given position.
503 pub fn type_of(&self, frange: FileRange) -> Cancelable<Option<String>> {
504 self.with_db(|db| hover::type_of(db, frange))?
507 /// Returns the edit required to rename reference at the position to the new
511 position: FilePosition,
513 ) -> Cancelable<Vec<SourceFileEdit>> {
514 self.with_db(|db| db.rename(position, new_name))?
517 fn with_db<F: FnOnce(&db::RootDatabase) -> T + std::panic::UnwindSafe, T>(
521 self.db.catch_canceled(f)
525 pub struct LibraryData {
526 root_id: SourceRootId,
527 root_change: RootChange,
528 symbol_index: SymbolIndex,
531 impl fmt::Debug for LibraryData {
532 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
533 f.debug_struct("LibraryData")
534 .field("root_id", &self.root_id)
535 .field("root_change", &self.root_change)
536 .field("n_symbols", &self.symbol_index.len())
543 root_id: SourceRootId,
544 files: Vec<(FileId, RelativePathBuf, Arc<String>)>,
546 let symbol_index = SymbolIndex::for_files(files.par_iter().map(|(file_id, _, text)| {
547 let file = SourceFile::parse(text);
550 let mut root_change = RootChange::default();
551 root_change.added = files
553 .map(|(file_id, path, text)| AddFile {
568 fn analysis_is_send() {
569 fn is_send<T: Send>() {}
570 is_send::<Analysis>();