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};
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()
124 pub fn add_root(&mut self, root_id: SourceRootId, is_local: bool) {
125 self.new_roots.push((root_id, is_local));
129 root_id: SourceRootId,
131 path: RelativePathBuf,
145 pub fn change_file(&mut self, file_id: FileId, new_text: Arc<String>) {
146 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 };
156 pub fn add_library(&mut self, data: LibraryData) {
157 self.libraries_added.push(data)
159 pub fn set_crate_graph(&mut self, graph: CrateGraph) {
160 self.crate_graph = Some(graph);
165 pub struct SourceChange {
167 pub source_file_edits: Vec<SourceFileEdit>,
168 pub file_system_edits: Vec<FileSystemEdit>,
169 pub cursor_position: Option<FilePosition>,
173 pub struct SourceFileEdit {
179 pub enum FileSystemEdit {
181 source_root: SourceRootId,
182 path: RelativePathBuf,
186 dst_source_root: SourceRootId,
187 dst_path: RelativePathBuf,
192 pub struct Diagnostic {
194 pub range: TextRange,
195 pub fix: Option<SourceChange>,
196 pub severity: Severity,
210 pub fn new(query: String) -> Query {
211 let lowercased = query.to_lowercase();
218 limit: usize::max_value(),
221 pub fn only_types(&mut self) {
222 self.only_types = true;
224 pub fn libs(&mut self) {
227 pub fn exact(&mut self) {
230 pub fn limit(&mut self, limit: usize) {
235 /// `NavigationTarget` represents and element in the editor's UI whihc you can
236 /// click on to navigate to a particular piece of code.
238 /// Typically, a `NavigationTarget` corresponds to some element in the source
239 /// code, like a function or a struct, but this is not strictly required.
240 #[derive(Debug, Clone)]
241 pub struct NavigationTarget {
246 // Should be DefId ideally
247 ptr: Option<LocalSyntaxPtr>,
250 impl NavigationTarget {
251 fn from_symbol(symbol: FileSymbol) -> NavigationTarget {
253 file_id: symbol.file_id,
254 name: symbol.name.clone(),
255 kind: symbol.ptr.kind(),
256 range: symbol.ptr.range(),
257 ptr: Some(symbol.ptr.clone()),
260 pub fn name(&self) -> &SmolStr {
263 pub fn kind(&self) -> SyntaxKind {
266 pub fn file_id(&self) -> FileId {
269 pub fn range(&self) -> TextRange {
275 pub struct RangeInfo<T> {
276 pub range: TextRange,
280 impl<T> RangeInfo<T> {
281 fn new(range: TextRange, info: T) -> RangeInfo<T> {
282 RangeInfo { range, info }
287 pub struct CallInfo {
289 pub doc: Option<String>,
290 pub parameters: Vec<String>,
291 pub active_parameter: Option<usize>,
294 /// `AnalysisHost` stores the current state of the world.
295 #[derive(Debug, Default)]
296 pub struct AnalysisHost {
297 db: db::RootDatabase,
301 /// Returns a snapshot of the current state, which you can query for
302 /// semantic information.
303 pub fn analysis(&self) -> Analysis {
305 db: self.db.snapshot(),
308 /// Applies changes to the current state of the world. If there are
309 /// outstanding snapshots, they will be canceled.
310 pub fn apply_change(&mut self, change: AnalysisChange) {
311 self.db.apply_change(change)
315 /// Analysis is a snapshot of a world state at a moment in time. It is the main
316 /// entry point for asking semantic information about the world. When the world
317 /// state is advanced using `AnalysisHost::apply_change` method, all existing
318 /// `Analysis` are canceled (most method return `Err(Canceled)`).
320 pub struct Analysis {
321 db: salsa::Snapshot<db::RootDatabase>,
325 /// Gets the text of the source file.
326 pub fn file_text(&self, file_id: FileId) -> Arc<String> {
327 self.db.file_text(file_id)
329 /// Gets the syntax tree of the file.
330 pub fn file_syntax(&self, file_id: FileId) -> TreePtr<SourceFile> {
331 self.db.source_file(file_id).clone()
333 /// Gets the file's `LineIndex`: data structure to convert between absolute
334 /// offsets and line/column representation.
335 pub fn file_line_index(&self, file_id: FileId) -> Arc<LineIndex> {
336 self.db.line_index(file_id)
338 /// Selects the next syntactic nodes encopasing the range.
339 pub fn extend_selection(&self, frange: FileRange) -> TextRange {
340 extend_selection::extend_selection(&self.db, frange)
342 /// Returns position of the mathcing brace (all types of braces are
344 pub fn matching_brace(&self, file: &SourceFile, offset: TextUnit) -> Option<TextUnit> {
345 ra_ide_api_light::matching_brace(file, offset)
347 /// Returns a syntax tree represented as `String`, for debug purposes.
348 // FIXME: use a better name here.
349 pub fn syntax_tree(&self, file_id: FileId) -> String {
350 let file = self.db.source_file(file_id);
351 ra_ide_api_light::syntax_tree(&file)
353 /// Returns an edit to remove all newlines in the range, cleaning up minor
354 /// stuff like trailing commas.
355 pub fn join_lines(&self, frange: FileRange) -> SourceChange {
356 let file = self.db.source_file(frange.file_id);
357 SourceChange::from_local_edit(
359 ra_ide_api_light::join_lines(&file, frange.range),
362 /// Returns an edit which should be applied when opening a new line, fixing
363 /// up minor stuff like continuing the comment.
364 pub fn on_enter(&self, position: FilePosition) -> Option<SourceChange> {
365 let file = self.db.source_file(position.file_id);
366 let edit = ra_ide_api_light::on_enter(&file, position.offset)?;
367 Some(SourceChange::from_local_edit(position.file_id, edit))
369 /// Returns an edit which should be applied after `=` was typed. Primarily,
370 /// this works when adding `let =`.
371 // FIXME: use a snippet completion instead of this hack here.
372 pub fn on_eq_typed(&self, position: FilePosition) -> Option<SourceChange> {
373 let file = self.db.source_file(position.file_id);
374 let edit = ra_ide_api_light::on_eq_typed(&file, position.offset)?;
375 Some(SourceChange::from_local_edit(position.file_id, edit))
377 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
378 pub fn on_dot_typed(&self, position: FilePosition) -> Option<SourceChange> {
379 let file = self.db.source_file(position.file_id);
380 let edit = ra_ide_api_light::on_dot_typed(&file, position.offset)?;
381 Some(SourceChange::from_local_edit(position.file_id, edit))
383 /// Returns a tree representation of symbols in the file. Useful to draw a
385 pub fn file_structure(&self, file_id: FileId) -> Vec<StructureNode> {
386 let file = self.db.source_file(file_id);
387 ra_ide_api_light::file_structure(&file)
389 /// Returns the set of folding ranges.
390 pub fn folding_ranges(&self, file_id: FileId) -> Vec<Fold> {
391 let file = self.db.source_file(file_id);
392 ra_ide_api_light::folding_ranges(&file)
394 /// Fuzzy searches for a symbol.
395 pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
396 let res = symbol_index::world_symbols(&*self.db, query)?
398 .map(NavigationTarget::from_symbol)
402 pub fn goto_defenition(
404 position: FilePosition,
405 ) -> Cancelable<Option<Vec<NavigationTarget>>> {
406 goto_defenition::goto_defenition(&*self.db, position)
408 /// Finds all usages of the reference at point.
409 pub fn find_all_refs(&self, position: FilePosition) -> Cancelable<Vec<(FileId, TextRange)>> {
410 self.db.find_all_refs(position)
412 /// Returns a short text descrbing element at position.
413 pub fn hover(&self, position: FilePosition) -> Cancelable<Option<RangeInfo<String>>> {
414 hover::hover(&*self.db, position)
416 /// Computes parameter information for the given call expression.
417 pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
418 call_info::call_info(&*self.db, position)
420 /// Returns a `mod name;` declaration which created the current module.
421 pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
422 self.db.parent_module(position)
424 /// Returns crates this file belongs too.
425 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
426 self.db.crate_for(file_id)
428 /// Returns the root file of the given crate.
429 pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
430 Ok(self.db.crate_graph().crate_root(crate_id))
432 /// Returns the set of possible targets to run for the current file.
433 pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
434 runnables::runnables(&*self.db, file_id)
436 /// Computes syntax highlighting for the given file.
437 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HighlightedRange>> {
438 syntax_highlighting::highlight(&*self.db, file_id)
440 /// Computes completions at the given position.
441 pub fn completions(&self, position: FilePosition) -> Cancelable<Option<Vec<CompletionItem>>> {
442 let completions = completion::completions(&self.db, position)?;
443 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))
450 /// Computes the set of diagnostics for the given file.
451 pub fn diagnostics(&self, file_id: FileId) -> Cancelable<Vec<Diagnostic>> {
452 self.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 hover::type_of(&*self.db, frange)
458 /// Returns the edit required to rename reference at the position to the new
462 position: FilePosition,
464 ) -> Cancelable<Vec<SourceFileEdit>> {
465 self.db.rename(position, new_name)
469 pub struct LibraryData {
470 root_id: SourceRootId,
471 root_change: RootChange,
472 symbol_index: SymbolIndex,
475 impl fmt::Debug for LibraryData {
476 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
477 f.debug_struct("LibraryData")
478 .field("root_id", &self.root_id)
479 .field("root_change", &self.root_change)
480 .field("n_symbols", &self.symbol_index.len())
487 root_id: SourceRootId,
488 files: Vec<(FileId, RelativePathBuf, Arc<String>)>,
490 let symbol_index = SymbolIndex::for_files(files.par_iter().map(|(file_id, _, text)| {
491 let file = SourceFile::parse(text);
494 let mut root_change = RootChange::default();
495 root_change.added = files
497 .map(|(file_id, path, text)| AddFile {
512 fn analysis_is_send() {
513 fn is_send<T: Send>() {}
514 is_send::<Analysis>();