1 //! ra_analyzer crate provides "ide-centric" APIs for the rust-analyzer. What
2 //! powers this API are the `RootDatabase` struct, which defines a `salsa`
3 //! database, and the `ra_hir` crate, where majority of the analysis happens.
4 //! However, IDE specific bits of the analysis (most notably completion) happen
9 None => return Ok(None),
19 pub mod mock_analysis;
26 mod syntax_highlighting;
28 use std::{fmt, sync::Arc};
30 use ra_syntax::{SmolStr, SourceFile, TreePtr, SyntaxKind, TextRange, TextUnit};
31 use ra_text_edit::TextEdit;
32 use ra_db::{SyntaxDatabase, FilesDatabase, LocalSyntaxPtr};
33 use rayon::prelude::*;
34 use relative_path::RelativePathBuf;
35 use rustc_hash::FxHashMap;
36 use salsa::ParallelDatabase;
39 symbol_index::{FileSymbol, SymbolIndex},
40 db::LineIndexDatabase,
44 completion::{CompletionItem, CompletionItemKind, InsertText},
45 runnables::{Runnable, RunnableKind},
47 pub use ra_ide_api_light::{
48 Fold, FoldKind, HighlightedRange, Severity, StructureNode,
49 LineIndex, LineCol, translate_offset_with_edit,
52 Cancelable, Canceled, CrateGraph, CrateId, FileId, FilePosition, FileRange, SourceRootId
56 pub struct AnalysisChange {
57 new_roots: Vec<(SourceRootId, bool)>,
58 roots_changed: FxHashMap<SourceRootId, RootChange>,
59 files_changed: Vec<(FileId, Arc<String>)>,
60 libraries_added: Vec<LibraryData>,
61 crate_graph: Option<CrateGraph>,
67 removed: Vec<RemoveFile>,
73 path: RelativePathBuf,
80 path: RelativePathBuf,
83 impl fmt::Debug for AnalysisChange {
84 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
85 let mut d = fmt.debug_struct("AnalysisChange");
86 if !self.new_roots.is_empty() {
87 d.field("new_roots", &self.new_roots);
89 if !self.roots_changed.is_empty() {
90 d.field("roots_changed", &self.roots_changed);
92 if !self.files_changed.is_empty() {
93 d.field("files_changed", &self.files_changed.len());
95 if !self.libraries_added.is_empty() {
96 d.field("libraries_added", &self.libraries_added.len());
98 if !self.crate_graph.is_some() {
99 d.field("crate_graph", &self.crate_graph);
105 impl fmt::Debug for RootChange {
106 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
107 fmt.debug_struct("AnalysisChange")
108 .field("added", &self.added.len())
109 .field("removed", &self.removed.len())
114 impl AnalysisChange {
115 pub fn new() -> AnalysisChange {
116 AnalysisChange::default()
118 pub fn add_root(&mut self, root_id: SourceRootId, is_local: bool) {
119 self.new_roots.push((root_id, is_local));
123 root_id: SourceRootId,
125 path: RelativePathBuf,
139 pub fn change_file(&mut self, file_id: FileId, new_text: Arc<String>) {
140 self.files_changed.push((file_id, new_text))
142 pub fn remove_file(&mut self, root_id: SourceRootId, file_id: FileId, path: RelativePathBuf) {
143 let file = RemoveFile { file_id, path };
150 pub fn add_library(&mut self, data: LibraryData) {
151 self.libraries_added.push(data)
153 pub fn set_crate_graph(&mut self, graph: CrateGraph) {
154 self.crate_graph = Some(graph);
159 pub struct SourceChange {
161 pub source_file_edits: Vec<SourceFileEdit>,
162 pub file_system_edits: Vec<FileSystemEdit>,
163 pub cursor_position: Option<FilePosition>,
167 pub struct SourceFileEdit {
173 pub enum FileSystemEdit {
175 source_root: SourceRootId,
176 path: RelativePathBuf,
180 dst_source_root: SourceRootId,
181 dst_path: RelativePathBuf,
186 pub struct Diagnostic {
188 pub range: TextRange,
189 pub fix: Option<SourceChange>,
190 pub severity: Severity,
204 pub fn new(query: String) -> Query {
205 let lowercased = query.to_lowercase();
212 limit: usize::max_value(),
215 pub fn only_types(&mut self) {
216 self.only_types = true;
218 pub fn libs(&mut self) {
221 pub fn exact(&mut self) {
224 pub fn limit(&mut self, limit: usize) {
229 /// `NavigationTarget` represents and element in the editor's UI whihc you can
230 /// click on to navigate to a particular piece of code.
232 /// Typically, a `NavigationTarget` corresponds to some element in the source
233 /// code, like a function or a struct, but this is not strictly required.
234 #[derive(Debug, Clone)]
235 pub struct NavigationTarget {
240 // Should be DefId ideally
241 ptr: Option<LocalSyntaxPtr>,
244 impl NavigationTarget {
245 fn from_symbol(symbol: FileSymbol) -> NavigationTarget {
247 file_id: symbol.file_id,
248 name: symbol.name.clone(),
249 kind: symbol.ptr.kind(),
250 range: symbol.ptr.range(),
251 ptr: Some(symbol.ptr.clone()),
254 pub fn name(&self) -> &SmolStr {
257 pub fn kind(&self) -> SyntaxKind {
260 pub fn file_id(&self) -> FileId {
263 pub fn range(&self) -> TextRange {
269 pub struct RangeInfo<T> {
270 pub range: TextRange,
274 impl<T> RangeInfo<T> {
275 fn new(range: TextRange, info: T) -> RangeInfo<T> {
276 RangeInfo { range, info }
281 pub struct CallInfo {
283 pub doc: Option<String>,
284 pub parameters: Vec<String>,
285 pub active_parameter: Option<usize>,
288 /// `AnalysisHost` stores the current state of the world.
289 #[derive(Debug, Default)]
290 pub struct AnalysisHost {
291 db: db::RootDatabase,
295 /// Returns a snapshot of the current state, which you can query for
296 /// semantic information.
297 pub fn analysis(&self) -> Analysis {
299 db: self.db.snapshot(),
302 /// Applies changes to the current state of the world. If there are
303 /// outstanding snapshots, they will be canceled.
304 pub fn apply_change(&mut self, change: AnalysisChange) {
305 self.db.apply_change(change)
309 /// Analysis is a snapshot of a world state at a moment in time. It is the main
310 /// entry point for asking semantic information about the world. When the world
311 /// state is advanced using `AnalysisHost::apply_change` method, all existing
312 /// `Analysis` are canceled (most method return `Err(Canceled)`).
314 pub struct Analysis {
315 db: salsa::Snapshot<db::RootDatabase>,
319 /// Gets the text of the source file.
320 pub fn file_text(&self, file_id: FileId) -> Arc<String> {
321 self.db.file_text(file_id)
323 /// Gets the syntax tree of the file.
324 pub fn file_syntax(&self, file_id: FileId) -> TreePtr<SourceFile> {
325 self.db.source_file(file_id).clone()
327 /// Gets the file's `LineIndex`: data structure to convert between absolute
328 /// offsets and line/column representation.
329 pub fn file_line_index(&self, file_id: FileId) -> Arc<LineIndex> {
330 self.db.line_index(file_id)
332 /// Selects the next syntactic nodes encopasing the range.
333 pub fn extend_selection(&self, frange: FileRange) -> TextRange {
334 extend_selection::extend_selection(&self.db, frange)
336 /// Returns position of the mathcing brace (all types of braces are
338 pub fn matching_brace(&self, file: &SourceFile, offset: TextUnit) -> Option<TextUnit> {
339 ra_ide_api_light::matching_brace(file, offset)
341 /// Returns a syntax tree represented as `String`, for debug purposes.
342 // FIXME: use a better name here.
343 pub fn syntax_tree(&self, file_id: FileId) -> String {
344 let file = self.db.source_file(file_id);
345 ra_ide_api_light::syntax_tree(&file)
347 /// Returns an edit to remove all newlines in the range, cleaning up minor
348 /// stuff like trailing commas.
349 pub fn join_lines(&self, frange: FileRange) -> SourceChange {
350 let file = self.db.source_file(frange.file_id);
351 SourceChange::from_local_edit(
353 ra_ide_api_light::join_lines(&file, frange.range),
356 /// Returns an edit which should be applied when opening a new line, fixing
357 /// up minor stuff like continuing the comment.
358 pub fn on_enter(&self, position: FilePosition) -> Option<SourceChange> {
359 let file = self.db.source_file(position.file_id);
360 let edit = ra_ide_api_light::on_enter(&file, position.offset)?;
361 Some(SourceChange::from_local_edit(position.file_id, edit))
363 /// Returns an edit which should be applied after `=` was typed. Primarily,
364 /// this works when adding `let =`.
365 // FIXME: use a snippet completion instead of this hack here.
366 pub fn on_eq_typed(&self, position: FilePosition) -> Option<SourceChange> {
367 let file = self.db.source_file(position.file_id);
368 let edit = ra_ide_api_light::on_eq_typed(&file, position.offset)?;
369 Some(SourceChange::from_local_edit(position.file_id, edit))
371 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
372 pub fn on_dot_typed(&self, position: FilePosition) -> Option<SourceChange> {
373 let file = self.db.source_file(position.file_id);
374 let edit = ra_ide_api_light::on_dot_typed(&file, position.offset)?;
375 Some(SourceChange::from_local_edit(position.file_id, edit))
377 /// Returns a tree representation of symbols in the file. Useful to draw a
379 pub fn file_structure(&self, file_id: FileId) -> Vec<StructureNode> {
380 let file = self.db.source_file(file_id);
381 ra_ide_api_light::file_structure(&file)
383 /// Returns the set of folding ranges.
384 pub fn folding_ranges(&self, file_id: FileId) -> Vec<Fold> {
385 let file = self.db.source_file(file_id);
386 ra_ide_api_light::folding_ranges(&file)
388 /// Fuzzy searches for a symbol.
389 pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
390 let res = symbol_index::world_symbols(&*self.db, query)?
392 .map(NavigationTarget::from_symbol)
396 pub fn goto_defenition(
398 position: FilePosition,
399 ) -> Cancelable<Option<Vec<NavigationTarget>>> {
400 goto_defenition::goto_defenition(&*self.db, position)
402 /// Finds all usages of the reference at point.
403 pub fn find_all_refs(&self, position: FilePosition) -> Cancelable<Vec<(FileId, TextRange)>> {
404 self.db.find_all_refs(position)
406 /// Returns a short text descrbing element at position.
407 pub fn hover(&self, position: FilePosition) -> Cancelable<Option<RangeInfo<String>>> {
408 hover::hover(&*self.db, position)
410 /// Computes parameter information for the given call expression.
411 pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
412 call_info::call_info(&*self.db, position)
414 /// Returns a `mod name;` declaration which created the current module.
415 pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
416 self.db.parent_module(position)
418 /// Returns crates this file belongs too.
419 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
420 self.db.crate_for(file_id)
422 /// Returns the root file of the given crate.
423 pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
424 Ok(self.db.crate_graph().crate_root(crate_id))
426 /// Returns the set of possible targets to run for the current file.
427 pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
428 runnables::runnables(&*self.db, file_id)
430 /// Computes syntax highlighting for the given file.
431 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HighlightedRange>> {
432 syntax_highlighting::highlight(&*self.db, file_id)
434 /// Computes completions at the given position.
435 pub fn completions(&self, position: FilePosition) -> Cancelable<Option<Vec<CompletionItem>>> {
436 let completions = completion::completions(&self.db, position)?;
437 Ok(completions.map(|it| it.into()))
439 /// Computes assists (aks code actons aka intentions) for the given
441 pub fn assists(&self, frange: FileRange) -> Cancelable<Vec<SourceChange>> {
442 Ok(self.db.assists(frange))
444 /// Computes the set of diagnostics for the given file.
445 pub fn diagnostics(&self, file_id: FileId) -> Cancelable<Vec<Diagnostic>> {
446 self.db.diagnostics(file_id)
448 /// Computes the type of the expression at the given position.
449 pub fn type_of(&self, frange: FileRange) -> Cancelable<Option<String>> {
450 hover::type_of(&*self.db, frange)
452 /// Returns the edit required to rename reference at the position to the new
456 position: FilePosition,
458 ) -> Cancelable<Vec<SourceFileEdit>> {
459 self.db.rename(position, new_name)
463 pub struct LibraryData {
464 root_id: SourceRootId,
465 root_change: RootChange,
466 symbol_index: SymbolIndex,
469 impl fmt::Debug for LibraryData {
470 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
471 f.debug_struct("LibraryData")
472 .field("root_id", &self.root_id)
473 .field("root_change", &self.root_change)
474 .field("n_symbols", &self.symbol_index.len())
481 root_id: SourceRootId,
482 files: Vec<(FileId, RelativePathBuf, Arc<String>)>,
484 let symbol_index = SymbolIndex::for_files(files.par_iter().map(|(file_id, _, text)| {
485 let file = SourceFile::parse(text);
488 let mut root_change = RootChange::default();
489 root_change.added = files
491 .map(|(file_id, path, text)| AddFile {
506 fn analysis_is_send() {
507 fn is_send<T: Send>() {}
508 is_send::<Analysis>();