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