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