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