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