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