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