]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide_api/src/lib.rs
rename FilesDatabase -> SourceDatabase
[rust.git] / crates / ra_ide_api / src / lib.rs
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.
4 //!
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
8 //! in this crate.
9 //!
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.
12 mod db;
13 mod imp;
14 pub mod mock_analysis;
15 mod symbol_index;
16 mod navigation_target;
17
18 mod status;
19 mod completion;
20 mod runnables;
21 mod goto_definition;
22 mod extend_selection;
23 mod hover;
24 mod call_info;
25 mod syntax_highlighting;
26 mod parent_module;
27 mod rename;
28
29 #[cfg(test)]
30 mod marks;
31
32 use std::{fmt, sync::Arc};
33
34 use ra_syntax::{SourceFile, TreeArc, TextRange, TextUnit};
35 use ra_text_edit::TextEdit;
36 use ra_db::{
37     SourceDatabase, CheckCanceled,
38     salsa::{self, ParallelDatabase},
39 };
40 use rayon::prelude::*;
41 use relative_path::RelativePathBuf;
42 use rustc_hash::FxHashMap;
43
44 use crate::{
45     symbol_index::{FileSymbol, SymbolIndex},
46     db::LineIndexDatabase,
47 };
48
49 pub use crate::{
50     completion::{CompletionItem, CompletionItemKind, InsertTextFormat},
51     runnables::{Runnable, RunnableKind},
52     navigation_target::NavigationTarget,
53 };
54 pub use ra_ide_api_light::{
55     Fold, FoldKind, HighlightedRange, Severity, StructureNode,
56     LineIndex, LineCol, translate_offset_with_edit,
57 };
58 pub use ra_db::{
59     Canceled, CrateGraph, CrateId, FileId, FilePosition, FileRange, SourceRootId
60 };
61
62 pub type Cancelable<T> = Result<T, Canceled>;
63
64 #[derive(Default)]
65 pub struct AnalysisChange {
66     new_roots: Vec<(SourceRootId, bool)>,
67     roots_changed: FxHashMap<SourceRootId, RootChange>,
68     files_changed: Vec<(FileId, Arc<String>)>,
69     libraries_added: Vec<LibraryData>,
70     crate_graph: Option<CrateGraph>,
71 }
72
73 #[derive(Default)]
74 struct RootChange {
75     added: Vec<AddFile>,
76     removed: Vec<RemoveFile>,
77 }
78
79 #[derive(Debug)]
80 struct AddFile {
81     file_id: FileId,
82     path: RelativePathBuf,
83     text: Arc<String>,
84 }
85
86 #[derive(Debug)]
87 struct RemoveFile {
88     file_id: FileId,
89     path: RelativePathBuf,
90 }
91
92 impl fmt::Debug for AnalysisChange {
93     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
94         let mut d = fmt.debug_struct("AnalysisChange");
95         if !self.new_roots.is_empty() {
96             d.field("new_roots", &self.new_roots);
97         }
98         if !self.roots_changed.is_empty() {
99             d.field("roots_changed", &self.roots_changed);
100         }
101         if !self.files_changed.is_empty() {
102             d.field("files_changed", &self.files_changed.len());
103         }
104         if !self.libraries_added.is_empty() {
105             d.field("libraries_added", &self.libraries_added.len());
106         }
107         if !self.crate_graph.is_some() {
108             d.field("crate_graph", &self.crate_graph);
109         }
110         d.finish()
111     }
112 }
113
114 impl fmt::Debug for RootChange {
115     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
116         fmt.debug_struct("AnalysisChange")
117             .field("added", &self.added.len())
118             .field("removed", &self.removed.len())
119             .finish()
120     }
121 }
122
123 impl AnalysisChange {
124     pub fn new() -> AnalysisChange {
125         AnalysisChange::default()
126     }
127
128     pub fn add_root(&mut self, root_id: SourceRootId, is_local: bool) {
129         self.new_roots.push((root_id, is_local));
130     }
131
132     pub fn add_file(
133         &mut self,
134         root_id: SourceRootId,
135         file_id: FileId,
136         path: RelativePathBuf,
137         text: Arc<String>,
138     ) {
139         let file = AddFile {
140             file_id,
141             path,
142             text,
143         };
144         self.roots_changed
145             .entry(root_id)
146             .or_default()
147             .added
148             .push(file);
149     }
150
151     pub fn change_file(&mut self, file_id: FileId, new_text: Arc<String>) {
152         self.files_changed.push((file_id, new_text))
153     }
154
155     pub fn remove_file(&mut self, root_id: SourceRootId, file_id: FileId, path: RelativePathBuf) {
156         let file = RemoveFile { file_id, path };
157         self.roots_changed
158             .entry(root_id)
159             .or_default()
160             .removed
161             .push(file);
162     }
163
164     pub fn add_library(&mut self, data: LibraryData) {
165         self.libraries_added.push(data)
166     }
167
168     pub fn set_crate_graph(&mut self, graph: CrateGraph) {
169         self.crate_graph = Some(graph);
170     }
171 }
172
173 #[derive(Debug)]
174 pub struct SourceChange {
175     pub label: String,
176     pub source_file_edits: Vec<SourceFileEdit>,
177     pub file_system_edits: Vec<FileSystemEdit>,
178     pub cursor_position: Option<FilePosition>,
179 }
180
181 #[derive(Debug)]
182 pub struct SourceFileEdit {
183     pub file_id: FileId,
184     pub edit: TextEdit,
185 }
186
187 #[derive(Debug)]
188 pub enum FileSystemEdit {
189     CreateFile {
190         source_root: SourceRootId,
191         path: RelativePathBuf,
192     },
193     MoveFile {
194         src: FileId,
195         dst_source_root: SourceRootId,
196         dst_path: RelativePathBuf,
197     },
198 }
199
200 #[derive(Debug)]
201 pub struct Diagnostic {
202     pub message: String,
203     pub range: TextRange,
204     pub fix: Option<SourceChange>,
205     pub severity: Severity,
206 }
207
208 #[derive(Debug)]
209 pub struct Query {
210     query: String,
211     lowercased: String,
212     only_types: bool,
213     libs: bool,
214     exact: bool,
215     limit: usize,
216 }
217
218 impl Query {
219     pub fn new(query: String) -> Query {
220         let lowercased = query.to_lowercase();
221         Query {
222             query,
223             lowercased,
224             only_types: false,
225             libs: false,
226             exact: false,
227             limit: usize::max_value(),
228         }
229     }
230
231     pub fn only_types(&mut self) {
232         self.only_types = true;
233     }
234
235     pub fn libs(&mut self) {
236         self.libs = true;
237     }
238
239     pub fn exact(&mut self) {
240         self.exact = true;
241     }
242
243     pub fn limit(&mut self, limit: usize) {
244         self.limit = limit
245     }
246 }
247
248 #[derive(Debug)]
249 pub struct RangeInfo<T> {
250     pub range: TextRange,
251     pub info: T,
252 }
253
254 impl<T> RangeInfo<T> {
255     pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
256         RangeInfo { range, info }
257     }
258 }
259
260 #[derive(Debug)]
261 pub struct CallInfo {
262     pub label: String,
263     pub doc: Option<String>,
264     pub parameters: Vec<String>,
265     pub active_parameter: Option<usize>,
266 }
267
268 /// `AnalysisHost` stores the current state of the world.
269 #[derive(Debug, Default)]
270 pub struct AnalysisHost {
271     db: db::RootDatabase,
272 }
273
274 impl AnalysisHost {
275     /// Returns a snapshot of the current state, which you can query for
276     /// semantic information.
277     pub fn analysis(&self) -> Analysis {
278         Analysis {
279             db: self.db.snapshot(),
280         }
281     }
282
283     /// Applies changes to the current state of the world. If there are
284     /// outstanding snapshots, they will be canceled.
285     pub fn apply_change(&mut self, change: AnalysisChange) {
286         self.db.apply_change(change)
287     }
288
289     pub fn collect_garbage(&mut self) {
290         self.db.collect_garbage();
291     }
292 }
293
294 /// Analysis is a snapshot of a world state at a moment in time. It is the main
295 /// entry point for asking semantic information about the world. When the world
296 /// state is advanced using `AnalysisHost::apply_change` method, all existing
297 /// `Analysis` are canceled (most method return `Err(Canceled)`).
298 #[derive(Debug)]
299 pub struct Analysis {
300     db: salsa::Snapshot<db::RootDatabase>,
301 }
302
303 impl Analysis {
304     /// Debug info about the current state of the analysis
305     pub fn status(&self) -> String {
306         status::status(&*self.db)
307     }
308
309     /// Gets the text of the source file.
310     pub fn file_text(&self, file_id: FileId) -> Arc<String> {
311         self.db.file_text(file_id)
312     }
313
314     /// Gets the syntax tree of the file.
315     pub fn parse(&self, file_id: FileId) -> TreeArc<SourceFile> {
316         self.db.source_file(file_id).clone()
317     }
318
319     /// Gets the file's `LineIndex`: data structure to convert between absolute
320     /// offsets and line/column representation.
321     pub fn file_line_index(&self, file_id: FileId) -> Arc<LineIndex> {
322         self.db.line_index(file_id)
323     }
324
325     /// Selects the next syntactic nodes encopasing the range.
326     pub fn extend_selection(&self, frange: FileRange) -> Cancelable<TextRange> {
327         self.with_db(|db| extend_selection::extend_selection(db, frange))
328     }
329
330     /// Returns position of the mathcing brace (all types of braces are
331     /// supported).
332     pub fn matching_brace(&self, position: FilePosition) -> Option<TextUnit> {
333         let file = self.db.source_file(position.file_id);
334         ra_ide_api_light::matching_brace(&file, position.offset)
335     }
336
337     /// Returns a syntax tree represented as `String`, for debug purposes.
338     // FIXME: use a better name here.
339     pub fn syntax_tree(&self, file_id: FileId) -> String {
340         let file = self.db.source_file(file_id);
341         ra_ide_api_light::syntax_tree(&file)
342     }
343
344     /// Returns an edit to remove all newlines in the range, cleaning up minor
345     /// stuff like trailing commas.
346     pub fn join_lines(&self, frange: FileRange) -> SourceChange {
347         let file = self.db.source_file(frange.file_id);
348         SourceChange::from_local_edit(
349             frange.file_id,
350             ra_ide_api_light::join_lines(&file, frange.range),
351         )
352     }
353
354     /// Returns an edit which should be applied when opening a new line, fixing
355     /// up minor stuff like continuing the comment.
356     pub fn on_enter(&self, position: FilePosition) -> Option<SourceChange> {
357         let file = self.db.source_file(position.file_id);
358         let edit = ra_ide_api_light::on_enter(&file, position.offset)?;
359         Some(SourceChange::from_local_edit(position.file_id, edit))
360     }
361
362     /// Returns an edit which should be applied after `=` was typed. Primarily,
363     /// this works when adding `let =`.
364     // FIXME: use a snippet completion instead of this hack here.
365     pub fn on_eq_typed(&self, position: FilePosition) -> Option<SourceChange> {
366         let file = self.db.source_file(position.file_id);
367         let edit = ra_ide_api_light::on_eq_typed(&file, position.offset)?;
368         Some(SourceChange::from_local_edit(position.file_id, edit))
369     }
370
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))
376     }
377
378     /// Returns a tree representation of symbols in the file. Useful to draw a
379     /// file outline.
380     pub fn file_structure(&self, file_id: FileId) -> Vec<StructureNode> {
381         let file = self.db.source_file(file_id);
382         ra_ide_api_light::file_structure(&file)
383     }
384
385     /// Returns the set of folding ranges.
386     pub fn folding_ranges(&self, file_id: FileId) -> Vec<Fold> {
387         let file = self.db.source_file(file_id);
388         ra_ide_api_light::folding_ranges(&file)
389     }
390
391     /// Fuzzy searches for a symbol.
392     pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
393         self.with_db(|db| {
394             symbol_index::world_symbols(db, query)
395                 .into_iter()
396                 .map(NavigationTarget::from_symbol)
397                 .collect::<Vec<_>>()
398         })
399     }
400
401     pub fn goto_definition(
402         &self,
403         position: FilePosition,
404     ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
405         self.with_db(|db| goto_definition::goto_definition(db, position))
406     }
407
408     /// Finds all usages of the reference at point.
409     pub fn find_all_refs(&self, position: FilePosition) -> Cancelable<Vec<(FileId, TextRange)>> {
410         self.with_db(|db| db.find_all_refs(position))
411     }
412
413     /// Returns a short text descrbing element at position.
414     pub fn hover(&self, position: FilePosition) -> Cancelable<Option<RangeInfo<String>>> {
415         self.with_db(|db| hover::hover(db, position))
416     }
417
418     /// Computes parameter information for the given call expression.
419     pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
420         self.with_db(|db| call_info::call_info(db, position))
421     }
422
423     /// Returns a `mod name;` declaration which created the current module.
424     pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
425         self.with_db(|db| parent_module::parent_module(db, position))
426     }
427
428     /// Returns crates this file belongs too.
429     pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
430         self.with_db(|db| db.crate_for(file_id))
431     }
432
433     /// Returns the root file of the given crate.
434     pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
435         self.with_db(|db| db.crate_graph().crate_root(crate_id))
436     }
437
438     /// Returns the set of possible targets to run for the current file.
439     pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
440         self.with_db(|db| runnables::runnables(db, file_id))
441     }
442
443     /// Computes syntax highlighting for the given file.
444     pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HighlightedRange>> {
445         self.with_db(|db| syntax_highlighting::highlight(db, file_id))
446     }
447
448     /// Computes completions at the given position.
449     pub fn completions(&self, position: FilePosition) -> Cancelable<Option<Vec<CompletionItem>>> {
450         self.with_db(|db| completion::completions(db, position).map(Into::into))
451     }
452
453     /// Computes assists (aks code actons aka intentions) for the given
454     /// position.
455     pub fn assists(&self, frange: FileRange) -> Cancelable<Vec<SourceChange>> {
456         self.with_db(|db| db.assists(frange))
457     }
458
459     /// Computes the set of diagnostics for the given file.
460     pub fn diagnostics(&self, file_id: FileId) -> Cancelable<Vec<Diagnostic>> {
461         self.with_db(|db| db.diagnostics(file_id))
462     }
463
464     /// Computes the type of the expression at the given position.
465     pub fn type_of(&self, frange: FileRange) -> Cancelable<Option<String>> {
466         self.with_db(|db| hover::type_of(db, frange))
467     }
468
469     /// Returns the edit required to rename reference at the position to the new
470     /// name.
471     pub fn rename(
472         &self,
473         position: FilePosition,
474         new_name: &str,
475     ) -> Cancelable<Option<SourceChange>> {
476         self.with_db(|db| rename::rename(db, position, new_name))
477     }
478
479     fn with_db<F: FnOnce(&db::RootDatabase) -> T + std::panic::UnwindSafe, T>(
480         &self,
481         f: F,
482     ) -> Cancelable<T> {
483         self.db.catch_canceled(f)
484     }
485 }
486
487 pub struct LibraryData {
488     root_id: SourceRootId,
489     root_change: RootChange,
490     symbol_index: SymbolIndex,
491 }
492
493 impl fmt::Debug for LibraryData {
494     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
495         f.debug_struct("LibraryData")
496             .field("root_id", &self.root_id)
497             .field("root_change", &self.root_change)
498             .field("n_symbols", &self.symbol_index.len())
499             .finish()
500     }
501 }
502
503 impl LibraryData {
504     pub fn prepare(
505         root_id: SourceRootId,
506         files: Vec<(FileId, RelativePathBuf, Arc<String>)>,
507     ) -> LibraryData {
508         let symbol_index = SymbolIndex::for_files(files.par_iter().map(|(file_id, _, text)| {
509             let file = SourceFile::parse(text);
510             (*file_id, file)
511         }));
512         let mut root_change = RootChange::default();
513         root_change.added = files
514             .into_iter()
515             .map(|(file_id, path, text)| AddFile {
516                 file_id,
517                 path,
518                 text,
519             })
520             .collect();
521         LibraryData {
522             root_id,
523             root_change,
524             symbol_index,
525         }
526     }
527 }
528
529 #[test]
530 fn analysis_is_send() {
531     fn is_send<T: Send>() {}
532     is_send::<Analysis>();
533 }