]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide_api/src/lib.rs
make matching brace consistent
[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, InsertText},
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, position: FilePosition) -> Option<TextUnit> {
320         let file = self.db.source_file(position.file_id);
321         ra_ide_api_light::matching_brace(&file, position.offset)
322     }
323
324     /// Returns a syntax tree represented as `String`, for debug purposes.
325     // FIXME: use a better name here.
326     pub fn syntax_tree(&self, file_id: FileId) -> String {
327         let file = self.db.source_file(file_id);
328         ra_ide_api_light::syntax_tree(&file)
329     }
330
331     /// Returns an edit to remove all newlines in the range, cleaning up minor
332     /// stuff like trailing commas.
333     pub fn join_lines(&self, frange: FileRange) -> SourceChange {
334         let file = self.db.source_file(frange.file_id);
335         SourceChange::from_local_edit(
336             frange.file_id,
337             ra_ide_api_light::join_lines(&file, frange.range),
338         )
339     }
340
341     /// Returns an edit which should be applied when opening a new line, fixing
342     /// up minor stuff like continuing the comment.
343     pub fn on_enter(&self, position: FilePosition) -> Option<SourceChange> {
344         let file = self.db.source_file(position.file_id);
345         let edit = ra_ide_api_light::on_enter(&file, position.offset)?;
346         Some(SourceChange::from_local_edit(position.file_id, edit))
347     }
348
349     /// Returns an edit which should be applied after `=` was typed. Primarily,
350     /// this works when adding `let =`.
351     // FIXME: use a snippet completion instead of this hack here.
352     pub fn on_eq_typed(&self, position: FilePosition) -> Option<SourceChange> {
353         let file = self.db.source_file(position.file_id);
354         let edit = ra_ide_api_light::on_eq_typed(&file, position.offset)?;
355         Some(SourceChange::from_local_edit(position.file_id, edit))
356     }
357
358     /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
359     pub fn on_dot_typed(&self, position: FilePosition) -> Option<SourceChange> {
360         let file = self.db.source_file(position.file_id);
361         let edit = ra_ide_api_light::on_dot_typed(&file, position.offset)?;
362         Some(SourceChange::from_local_edit(position.file_id, edit))
363     }
364
365     /// Returns a tree representation of symbols in the file. Useful to draw a
366     /// file outline.
367     pub fn file_structure(&self, file_id: FileId) -> Vec<StructureNode> {
368         let file = self.db.source_file(file_id);
369         ra_ide_api_light::file_structure(&file)
370     }
371
372     /// Returns the set of folding ranges.
373     pub fn folding_ranges(&self, file_id: FileId) -> Vec<Fold> {
374         let file = self.db.source_file(file_id);
375         ra_ide_api_light::folding_ranges(&file)
376     }
377
378     /// Fuzzy searches for a symbol.
379     pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
380         self.with_db(|db| {
381             symbol_index::world_symbols(db, query)
382                 .into_iter()
383                 .map(NavigationTarget::from_symbol)
384                 .collect::<Vec<_>>()
385         })
386     }
387
388     pub fn goto_definition(
389         &self,
390         position: FilePosition,
391     ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
392         self.with_db(|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.with_db(|db| call_info::call_info(db, position))
408     }
409
410     /// Returns a `mod name;` declaration which created the current module.
411     pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
412         self.with_db(|db| parent_module::parent_module(db, position))
413     }
414
415     /// Returns crates this file belongs too.
416     pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
417         self.with_db(|db| db.crate_for(file_id))
418     }
419
420     /// Returns the root file of the given crate.
421     pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
422         self.with_db(|db| db.crate_graph().crate_root(crate_id))
423     }
424
425     /// Returns the set of possible targets to run for the current file.
426     pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
427         self.with_db(|db| runnables::runnables(db, file_id))
428     }
429
430     /// Computes syntax highlighting for the given file.
431     pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HighlightedRange>> {
432         self.with_db(|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         self.with_db(|db| completion::completions(db, position).map(Into::into))
438     }
439
440     /// Computes assists (aks code actons aka intentions) for the given
441     /// position.
442     pub fn assists(&self, frange: FileRange) -> Cancelable<Vec<SourceChange>> {
443         self.with_db(|db| db.assists(frange))
444     }
445
446     /// Computes the set of diagnostics for the given file.
447     pub fn diagnostics(&self, file_id: FileId) -> Cancelable<Vec<Diagnostic>> {
448         self.with_db(|db| db.diagnostics(file_id))
449     }
450
451     /// Computes the type of the expression at the given position.
452     pub fn type_of(&self, frange: FileRange) -> Cancelable<Option<String>> {
453         self.with_db(|db| hover::type_of(db, frange))
454     }
455
456     /// Returns the edit required to rename reference at the position to the new
457     /// name.
458     pub fn rename(
459         &self,
460         position: FilePosition,
461         new_name: &str,
462     ) -> Cancelable<Option<SourceChange>> {
463         self.with_db(|db| rename::rename(db, position, new_name))
464     }
465
466     fn with_db<F: FnOnce(&db::RootDatabase) -> T + std::panic::UnwindSafe, T>(
467         &self,
468         f: F,
469     ) -> Cancelable<T> {
470         self.db.catch_canceled(f)
471     }
472 }
473
474 pub struct LibraryData {
475     root_id: SourceRootId,
476     root_change: RootChange,
477     symbol_index: SymbolIndex,
478 }
479
480 impl fmt::Debug for LibraryData {
481     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
482         f.debug_struct("LibraryData")
483             .field("root_id", &self.root_id)
484             .field("root_change", &self.root_change)
485             .field("n_symbols", &self.symbol_index.len())
486             .finish()
487     }
488 }
489
490 impl LibraryData {
491     pub fn prepare(
492         root_id: SourceRootId,
493         files: Vec<(FileId, RelativePathBuf, Arc<String>)>,
494     ) -> LibraryData {
495         let symbol_index = SymbolIndex::for_files(files.par_iter().map(|(file_id, _, text)| {
496             let file = SourceFile::parse(text);
497             (*file_id, file)
498         }));
499         let mut root_change = RootChange::default();
500         root_change.added = files
501             .into_iter()
502             .map(|(file_id, path, text)| AddFile {
503                 file_id,
504                 path,
505                 text,
506             })
507             .collect();
508         LibraryData {
509             root_id,
510             root_change,
511             symbol_index,
512         }
513     }
514 }
515
516 #[test]
517 fn analysis_is_send() {
518     fn is_send<T: Send>() {}
519     is_send::<Analysis>();
520 }