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