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),
23 pub mod mock_analysis;
32 mod syntax_highlighting;
34 use std::{fmt, sync::Arc};
36 use hir::{Def, ModuleSource, Name};
37 use ra_syntax::{SmolStr, SourceFile, TreePtr, SyntaxKind, SyntaxNode, TextRange, TextUnit, AstNode};
38 use ra_text_edit::TextEdit;
39 use ra_db::{SyntaxDatabase, FilesDatabase, LocalSyntaxPtr, BaseDatabase};
40 use rayon::prelude::*;
41 use relative_path::RelativePathBuf;
42 use rustc_hash::FxHashMap;
43 use salsa::ParallelDatabase;
46 symbol_index::{FileSymbol, SymbolIndex},
47 db::LineIndexDatabase,
51 completion::{CompletionItem, CompletionItemKind, InsertText},
52 runnables::{Runnable, RunnableKind},
54 pub use ra_ide_api_light::{
55 Fold, FoldKind, HighlightedRange, Severity, StructureNode,
56 LineIndex, LineCol, translate_offset_with_edit,
59 Cancelable, Canceled, CrateGraph, CrateId, FileId, FilePosition, FileRange, SourceRootId
63 pub struct AnalysisChange {
64 new_roots: Vec<(SourceRootId, bool)>,
65 roots_changed: FxHashMap<SourceRootId, RootChange>,
66 files_changed: Vec<(FileId, Arc<String>)>,
67 libraries_added: Vec<LibraryData>,
68 crate_graph: Option<CrateGraph>,
74 removed: Vec<RemoveFile>,
80 path: RelativePathBuf,
87 path: RelativePathBuf,
90 impl fmt::Debug for AnalysisChange {
91 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
92 let mut d = fmt.debug_struct("AnalysisChange");
93 if !self.new_roots.is_empty() {
94 d.field("new_roots", &self.new_roots);
96 if !self.roots_changed.is_empty() {
97 d.field("roots_changed", &self.roots_changed);
99 if !self.files_changed.is_empty() {
100 d.field("files_changed", &self.files_changed.len());
102 if !self.libraries_added.is_empty() {
103 d.field("libraries_added", &self.libraries_added.len());
105 if !self.crate_graph.is_some() {
106 d.field("crate_graph", &self.crate_graph);
112 impl fmt::Debug for RootChange {
113 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
114 fmt.debug_struct("AnalysisChange")
115 .field("added", &self.added.len())
116 .field("removed", &self.removed.len())
121 impl AnalysisChange {
122 pub fn new() -> AnalysisChange {
123 AnalysisChange::default()
126 pub fn add_root(&mut self, root_id: SourceRootId, is_local: bool) {
127 self.new_roots.push((root_id, is_local));
132 root_id: SourceRootId,
134 path: RelativePathBuf,
149 pub fn change_file(&mut self, file_id: FileId, new_text: Arc<String>) {
150 self.files_changed.push((file_id, new_text))
153 pub fn remove_file(&mut self, root_id: SourceRootId, file_id: FileId, path: RelativePathBuf) {
154 let file = RemoveFile { file_id, path };
162 pub fn add_library(&mut self, data: LibraryData) {
163 self.libraries_added.push(data)
166 pub fn set_crate_graph(&mut self, graph: CrateGraph) {
167 self.crate_graph = Some(graph);
172 pub struct SourceChange {
174 pub source_file_edits: Vec<SourceFileEdit>,
175 pub file_system_edits: Vec<FileSystemEdit>,
176 pub cursor_position: Option<FilePosition>,
180 pub struct SourceFileEdit {
186 pub enum FileSystemEdit {
188 source_root: SourceRootId,
189 path: RelativePathBuf,
193 dst_source_root: SourceRootId,
194 dst_path: RelativePathBuf,
199 pub struct Diagnostic {
201 pub range: TextRange,
202 pub fix: Option<SourceChange>,
203 pub severity: Severity,
217 pub fn new(query: String) -> Query {
218 let lowercased = query.to_lowercase();
225 limit: usize::max_value(),
229 pub fn only_types(&mut self) {
230 self.only_types = true;
233 pub fn libs(&mut self) {
237 pub fn exact(&mut self) {
241 pub fn limit(&mut self, limit: usize) {
246 /// `NavigationTarget` represents and element in the editor's UI whihc you can
247 /// click on to navigate to a particular piece of code.
249 /// Typically, a `NavigationTarget` corresponds to some element in the source
250 /// code, like a function or a struct, but this is not strictly required.
251 #[derive(Debug, Clone)]
252 pub struct NavigationTarget {
257 // Should be DefId ideally
258 ptr: Option<LocalSyntaxPtr>,
261 impl NavigationTarget {
262 fn from_symbol(symbol: FileSymbol) -> NavigationTarget {
264 file_id: symbol.file_id,
265 name: symbol.name.clone(),
266 kind: symbol.ptr.kind(),
267 range: symbol.ptr.range(),
268 ptr: Some(symbol.ptr.clone()),
272 fn from_syntax(name: Option<Name>, file_id: FileId, node: &SyntaxNode) -> NavigationTarget {
275 name: name.map(|n| n.to_string().into()).unwrap_or("".into()),
278 ptr: Some(LocalSyntaxPtr::new(node)),
281 // TODO once Def::Item is gone, this should be able to always return a NavigationTarget
282 fn from_def(db: &db::RootDatabase, def: Def) -> Cancelable<Option<NavigationTarget>> {
285 let (file_id, node) = s.source(db)?;
286 Some(NavigationTarget::from_syntax(
288 file_id.original_file(db),
293 let (file_id, node) = e.source(db)?;
294 Some(NavigationTarget::from_syntax(
296 file_id.original_file(db),
300 Def::EnumVariant(ev) => {
301 let (file_id, node) = ev.source(db)?;
302 Some(NavigationTarget::from_syntax(
304 file_id.original_file(db),
308 Def::Function(f) => {
309 let (file_id, node) = f.source(db)?;
310 let name = f.signature(db).name().clone();
311 Some(NavigationTarget::from_syntax(
313 file_id.original_file(db),
318 let (file_id, source) = m.definition_source(db)?;
319 let name = m.name(db)?;
321 ModuleSource::SourceFile(node) => {
322 Some(NavigationTarget::from_syntax(name, file_id, node.syntax()))
324 ModuleSource::Module(node) => {
325 Some(NavigationTarget::from_syntax(name, file_id, node.syntax()))
333 pub fn name(&self) -> &SmolStr {
337 pub fn kind(&self) -> SyntaxKind {
341 pub fn file_id(&self) -> FileId {
345 pub fn range(&self) -> TextRange {
351 pub struct RangeInfo<T> {
352 pub range: TextRange,
356 impl<T> RangeInfo<T> {
357 fn new(range: TextRange, info: T) -> RangeInfo<T> {
358 RangeInfo { range, info }
363 pub struct CallInfo {
365 pub doc: Option<String>,
366 pub parameters: Vec<String>,
367 pub active_parameter: Option<usize>,
370 /// `AnalysisHost` stores the current state of the world.
371 #[derive(Debug, Default)]
372 pub struct AnalysisHost {
373 db: db::RootDatabase,
377 /// Returns a snapshot of the current state, which you can query for
378 /// semantic information.
379 pub fn analysis(&self) -> Analysis {
381 db: self.db.snapshot(),
385 /// Applies changes to the current state of the world. If there are
386 /// outstanding snapshots, they will be canceled.
387 pub fn apply_change(&mut self, change: AnalysisChange) {
388 self.db.apply_change(change)
392 /// Analysis is a snapshot of a world state at a moment in time. It is the main
393 /// entry point for asking semantic information about the world. When the world
394 /// state is advanced using `AnalysisHost::apply_change` method, all existing
395 /// `Analysis` are canceled (most method return `Err(Canceled)`).
397 pub struct Analysis {
398 db: salsa::Snapshot<db::RootDatabase>,
402 /// Gets the text of the source file.
403 pub fn file_text(&self, file_id: FileId) -> Arc<String> {
404 self.db.file_text(file_id)
407 /// Gets the syntax tree of the file.
408 pub fn file_syntax(&self, file_id: FileId) -> TreePtr<SourceFile> {
409 self.db.source_file(file_id).clone()
412 /// Gets the file's `LineIndex`: data structure to convert between absolute
413 /// offsets and line/column representation.
414 pub fn file_line_index(&self, file_id: FileId) -> Arc<LineIndex> {
415 self.db.line_index(file_id)
418 /// Selects the next syntactic nodes encopasing the range.
419 pub fn extend_selection(&self, frange: FileRange) -> TextRange {
420 extend_selection::extend_selection(&self.db, frange)
423 /// Returns position of the mathcing brace (all types of braces are
425 pub fn matching_brace(&self, file: &SourceFile, offset: TextUnit) -> Option<TextUnit> {
426 ra_ide_api_light::matching_brace(file, offset)
429 /// Returns a syntax tree represented as `String`, for debug purposes.
430 // FIXME: use a better name here.
431 pub fn syntax_tree(&self, file_id: FileId) -> String {
432 let file = self.db.source_file(file_id);
433 ra_ide_api_light::syntax_tree(&file)
436 /// Returns an edit to remove all newlines in the range, cleaning up minor
437 /// stuff like trailing commas.
438 pub fn join_lines(&self, frange: FileRange) -> SourceChange {
439 let file = self.db.source_file(frange.file_id);
440 SourceChange::from_local_edit(
442 ra_ide_api_light::join_lines(&file, frange.range),
446 /// Returns an edit which should be applied when opening a new line, fixing
447 /// up minor stuff like continuing the comment.
448 pub fn on_enter(&self, position: FilePosition) -> Option<SourceChange> {
449 let file = self.db.source_file(position.file_id);
450 let edit = ra_ide_api_light::on_enter(&file, position.offset)?;
451 Some(SourceChange::from_local_edit(position.file_id, edit))
454 /// Returns an edit which should be applied after `=` was typed. Primarily,
455 /// this works when adding `let =`.
456 // FIXME: use a snippet completion instead of this hack here.
457 pub fn on_eq_typed(&self, position: FilePosition) -> Option<SourceChange> {
458 let file = self.db.source_file(position.file_id);
459 let edit = ra_ide_api_light::on_eq_typed(&file, position.offset)?;
460 Some(SourceChange::from_local_edit(position.file_id, edit))
463 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
464 pub fn on_dot_typed(&self, position: FilePosition) -> Option<SourceChange> {
465 let file = self.db.source_file(position.file_id);
466 let edit = ra_ide_api_light::on_dot_typed(&file, position.offset)?;
467 Some(SourceChange::from_local_edit(position.file_id, edit))
470 /// Returns a tree representation of symbols in the file. Useful to draw a
472 pub fn file_structure(&self, file_id: FileId) -> Vec<StructureNode> {
473 let file = self.db.source_file(file_id);
474 ra_ide_api_light::file_structure(&file)
477 /// Returns the set of folding ranges.
478 pub fn folding_ranges(&self, file_id: FileId) -> Vec<Fold> {
479 let file = self.db.source_file(file_id);
480 ra_ide_api_light::folding_ranges(&file)
483 /// Fuzzy searches for a symbol.
484 pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
486 let res = symbol_index::world_symbols(db, query)?
488 .map(NavigationTarget::from_symbol)
489 .collect::<Vec<_>>();
494 pub fn goto_definition(
496 position: FilePosition,
497 ) -> Cancelable<Option<Vec<NavigationTarget>>> {
499 .catch_canceled(|db| goto_definition::goto_definition(db, position))?
502 /// Finds all usages of the reference at point.
503 pub fn find_all_refs(&self, position: FilePosition) -> Cancelable<Vec<(FileId, TextRange)>> {
504 self.with_db(|db| db.find_all_refs(position))?
507 /// Returns a short text descrbing element at position.
508 pub fn hover(&self, position: FilePosition) -> Cancelable<Option<RangeInfo<String>>> {
509 self.with_db(|db| hover::hover(db, position))?
512 /// Computes parameter information for the given call expression.
513 pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
515 .catch_canceled(|db| call_info::call_info(db, position))?
518 /// Returns a `mod name;` declaration which created the current module.
519 pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
520 self.with_db(|db| db.parent_module(position))?
523 /// Returns crates this file belongs too.
524 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
525 self.with_db(|db| db.crate_for(file_id))?
528 /// Returns the root file of the given crate.
529 pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
530 Ok(self.db.crate_graph().crate_root(crate_id))
533 /// Returns the set of possible targets to run for the current file.
534 pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
536 .catch_canceled(|db| runnables::runnables(db, file_id))?
539 /// Computes syntax highlighting for the given file.
540 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HighlightedRange>> {
542 .catch_canceled(|db| syntax_highlighting::highlight(db, file_id))?
545 /// Computes completions at the given position.
546 pub fn completions(&self, position: FilePosition) -> Cancelable<Option<Vec<CompletionItem>>> {
547 let completions = self
549 .catch_canceled(|db| completion::completions(db, position))??;
550 Ok(completions.map(|it| it.into()))
553 /// Computes assists (aks code actons aka intentions) for the given
555 pub fn assists(&self, frange: FileRange) -> Cancelable<Vec<SourceChange>> {
556 Ok(self.db.assists(frange))
559 /// Computes the set of diagnostics for the given file.
560 pub fn diagnostics(&self, file_id: FileId) -> Cancelable<Vec<Diagnostic>> {
561 self.with_db(|db| db.diagnostics(file_id))?
564 /// Computes the type of the expression at the given position.
565 pub fn type_of(&self, frange: FileRange) -> Cancelable<Option<String>> {
566 self.with_db(|db| hover::type_of(db, frange))?
569 /// Returns the edit required to rename reference at the position to the new
573 position: FilePosition,
575 ) -> Cancelable<Vec<SourceFileEdit>> {
576 self.with_db(|db| db.rename(position, new_name))?
579 fn with_db<F: FnOnce(&db::RootDatabase) -> T + std::panic::UnwindSafe, T>(
583 self.db.catch_canceled(f)
587 pub struct LibraryData {
588 root_id: SourceRootId,
589 root_change: RootChange,
590 symbol_index: SymbolIndex,
593 impl fmt::Debug for LibraryData {
594 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
595 f.debug_struct("LibraryData")
596 .field("root_id", &self.root_id)
597 .field("root_change", &self.root_change)
598 .field("n_symbols", &self.symbol_index.len())
605 root_id: SourceRootId,
606 files: Vec<(FileId, RelativePathBuf, Arc<String>)>,
608 let symbol_index = SymbolIndex::for_files(files.par_iter().map(|(file_id, _, text)| {
609 let file = SourceFile::parse(text);
612 let mut root_change = RootChange::default();
613 root_change.added = files
615 .map(|(file_id, path, text)| AddFile {
630 fn analysis_is_send() {
631 fn is_send<T: Send>() {}
632 is_send::<Analysis>();