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