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