]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/lib.rs
f8d69382e03356f2ef38c95e70ff992dfd71529c
[rust.git] / crates / ide / src / lib.rs
1 //! ide 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 `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 // For proving that RootDatabase is RefUnwindSafe.
11 #![recursion_limit = "128"]
12
13 #[allow(unused)]
14 macro_rules! eprintln {
15     ($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
16 }
17
18 #[cfg(test)]
19 mod fixture;
20
21 mod markup;
22 mod prime_caches;
23 mod display;
24
25 mod call_hierarchy;
26 mod diagnostics;
27 mod expand_macro;
28 mod extend_selection;
29 mod file_structure;
30 mod folding_ranges;
31 mod goto_definition;
32 mod goto_implementation;
33 mod goto_type_definition;
34 mod view_hir;
35 mod hover;
36 mod inlay_hints;
37 mod join_lines;
38 mod matching_brace;
39 mod parent_module;
40 mod references;
41 mod fn_references;
42 mod runnables;
43 mod status;
44 mod syntax_highlighting;
45 mod syntax_tree;
46 mod typing;
47 mod markdown_remove;
48 mod doc_links;
49
50 use std::sync::Arc;
51
52 use cfg::CfgOptions;
53 use ide_db::base_db::{
54     salsa::{self, ParallelDatabase},
55     CheckCanceled, Env, FileLoader, FileSet, SourceDatabase, VfsPath,
56 };
57 use ide_db::{
58     symbol_index::{self, FileSymbol},
59     LineIndexDatabase,
60 };
61 use syntax::SourceFile;
62
63 use crate::display::ToNav;
64
65 pub use crate::{
66     call_hierarchy::CallItem,
67     diagnostics::{Diagnostic, DiagnosticsConfig, Fix, Severity},
68     display::navigation_target::{NavigationTarget, SymbolKind},
69     expand_macro::ExpandedMacro,
70     file_structure::StructureNode,
71     folding_ranges::{Fold, FoldKind},
72     hover::{HoverAction, HoverConfig, HoverGotoTypeData, HoverResult},
73     inlay_hints::{InlayHint, InlayHintsConfig, InlayKind},
74     markup::Markup,
75     prime_caches::PrimeCachesProgress,
76     references::{rename::RenameError, Declaration, ReferenceSearchResult},
77     runnables::{Runnable, RunnableKind, TestId},
78     syntax_highlighting::{
79         tags::{Highlight, HlMod, HlMods, HlPunct, HlTag},
80         HlRange,
81     },
82 };
83 pub use assists::{Assist, AssistConfig, AssistId, AssistKind};
84 pub use completion::{
85     CompletionConfig, CompletionItem, CompletionItemKind, CompletionScore, ImportEdit,
86     InsertTextFormat,
87 };
88 pub use hir::{Documentation, Semantics};
89 pub use ide_db::base_db::{
90     Canceled, Change, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange, SourceRoot,
91     SourceRootId,
92 };
93 pub use ide_db::{
94     call_info::CallInfo,
95     search::{FileReference, ReferenceAccess, ReferenceKind},
96 };
97 pub use ide_db::{
98     label::Label,
99     line_index::{LineCol, LineIndex},
100     search::SearchScope,
101     source_change::{FileSystemEdit, SourceChange},
102     symbol_index::Query,
103     RootDatabase,
104 };
105 pub use ssr::SsrError;
106 pub use syntax::{TextRange, TextSize};
107 pub use text_edit::{Indel, TextEdit};
108
109 pub type Cancelable<T> = Result<T, Canceled>;
110
111 /// Info associated with a text range.
112 #[derive(Debug)]
113 pub struct RangeInfo<T> {
114     pub range: TextRange,
115     pub info: T,
116 }
117
118 impl<T> RangeInfo<T> {
119     pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
120         RangeInfo { range, info }
121     }
122 }
123
124 /// `AnalysisHost` stores the current state of the world.
125 #[derive(Debug)]
126 pub struct AnalysisHost {
127     db: RootDatabase,
128 }
129
130 impl AnalysisHost {
131     pub fn new(lru_capacity: Option<usize>) -> AnalysisHost {
132         AnalysisHost { db: RootDatabase::new(lru_capacity) }
133     }
134
135     pub fn update_lru_capacity(&mut self, lru_capacity: Option<usize>) {
136         self.db.update_lru_capacity(lru_capacity);
137     }
138
139     /// Returns a snapshot of the current state, which you can query for
140     /// semantic information.
141     pub fn analysis(&self) -> Analysis {
142         Analysis { db: self.db.snapshot() }
143     }
144
145     /// Applies changes to the current state of the world. If there are
146     /// outstanding snapshots, they will be canceled.
147     pub fn apply_change(&mut self, change: Change) {
148         self.db.apply_change(change)
149     }
150
151     pub fn collect_garbage(&mut self) {
152         self.db.collect_garbage();
153     }
154     /// NB: this clears the database
155     pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes)> {
156         self.db.per_query_memory_usage()
157     }
158     pub fn request_cancellation(&mut self) {
159         self.db.request_cancellation();
160     }
161     pub fn raw_database(&self) -> &RootDatabase {
162         &self.db
163     }
164     pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
165         &mut self.db
166     }
167 }
168
169 impl Default for AnalysisHost {
170     fn default() -> AnalysisHost {
171         AnalysisHost::new(None)
172     }
173 }
174
175 /// Analysis is a snapshot of a world state at a moment in time. It is the main
176 /// entry point for asking semantic information about the world. When the world
177 /// state is advanced using `AnalysisHost::apply_change` method, all existing
178 /// `Analysis` are canceled (most method return `Err(Canceled)`).
179 #[derive(Debug)]
180 pub struct Analysis {
181     db: salsa::Snapshot<RootDatabase>,
182 }
183
184 // As a general design guideline, `Analysis` API are intended to be independent
185 // from the language server protocol. That is, when exposing some functionality
186 // we should think in terms of "what API makes most sense" and not in terms of
187 // "what types LSP uses". Although currently LSP is the only consumer of the
188 // API, the API should in theory be usable as a library, or via a different
189 // protocol.
190 impl Analysis {
191     // Creates an analysis instance for a single file, without any extenal
192     // dependencies, stdlib support or ability to apply changes. See
193     // `AnalysisHost` for creating a fully-featured analysis.
194     pub fn from_single_file(text: String) -> (Analysis, FileId) {
195         let mut host = AnalysisHost::default();
196         let file_id = FileId(0);
197         let mut file_set = FileSet::default();
198         file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_string()));
199         let source_root = SourceRoot::new_local(file_set);
200
201         let mut change = Change::new();
202         change.set_roots(vec![source_root]);
203         let mut crate_graph = CrateGraph::default();
204         // FIXME: cfg options
205         // Default to enable test for single file.
206         let mut cfg_options = CfgOptions::default();
207         cfg_options.insert_atom("test".into());
208         crate_graph.add_crate_root(
209             file_id,
210             Edition::Edition2018,
211             None,
212             cfg_options,
213             Env::default(),
214             Default::default(),
215         );
216         change.change_file(file_id, Some(Arc::new(text)));
217         change.set_crate_graph(crate_graph);
218         host.apply_change(change);
219         (host.analysis(), file_id)
220     }
221
222     /// Debug info about the current state of the analysis.
223     pub fn status(&self, file_id: Option<FileId>) -> Cancelable<String> {
224         self.with_db(|db| status::status(&*db, file_id))
225     }
226
227     pub fn prime_caches<F>(&self, cb: F) -> Cancelable<()>
228     where
229         F: Fn(PrimeCachesProgress) + Sync + std::panic::UnwindSafe,
230     {
231         self.with_db(move |db| prime_caches::prime_caches(db, &cb))
232     }
233
234     /// Gets the text of the source file.
235     pub fn file_text(&self, file_id: FileId) -> Cancelable<Arc<String>> {
236         self.with_db(|db| db.file_text(file_id))
237     }
238
239     /// Gets the syntax tree of the file.
240     pub fn parse(&self, file_id: FileId) -> Cancelable<SourceFile> {
241         self.with_db(|db| db.parse(file_id).tree())
242     }
243
244     /// Gets the file's `LineIndex`: data structure to convert between absolute
245     /// offsets and line/column representation.
246     pub fn file_line_index(&self, file_id: FileId) -> Cancelable<Arc<LineIndex>> {
247         self.with_db(|db| db.line_index(file_id))
248     }
249
250     /// Selects the next syntactic nodes encompassing the range.
251     pub fn extend_selection(&self, frange: FileRange) -> Cancelable<TextRange> {
252         self.with_db(|db| extend_selection::extend_selection(db, frange))
253     }
254
255     /// Returns position of the matching brace (all types of braces are
256     /// supported).
257     pub fn matching_brace(&self, position: FilePosition) -> Cancelable<Option<TextSize>> {
258         self.with_db(|db| {
259             let parse = db.parse(position.file_id);
260             let file = parse.tree();
261             matching_brace::matching_brace(&file, position.offset)
262         })
263     }
264
265     /// Returns a syntax tree represented as `String`, for debug purposes.
266     // FIXME: use a better name here.
267     pub fn syntax_tree(
268         &self,
269         file_id: FileId,
270         text_range: Option<TextRange>,
271     ) -> Cancelable<String> {
272         self.with_db(|db| syntax_tree::syntax_tree(&db, file_id, text_range))
273     }
274
275     pub fn view_hir(&self, position: FilePosition) -> Cancelable<String> {
276         self.with_db(|db| view_hir::view_hir(&db, position))
277     }
278
279     pub fn expand_macro(&self, position: FilePosition) -> Cancelable<Option<ExpandedMacro>> {
280         self.with_db(|db| expand_macro::expand_macro(db, position))
281     }
282
283     /// Returns an edit to remove all newlines in the range, cleaning up minor
284     /// stuff like trailing commas.
285     pub fn join_lines(&self, frange: FileRange) -> Cancelable<TextEdit> {
286         self.with_db(|db| {
287             let parse = db.parse(frange.file_id);
288             join_lines::join_lines(&parse.tree(), frange.range)
289         })
290     }
291
292     /// Returns an edit which should be applied when opening a new line, fixing
293     /// up minor stuff like continuing the comment.
294     /// The edit will be a snippet (with `$0`).
295     pub fn on_enter(&self, position: FilePosition) -> Cancelable<Option<TextEdit>> {
296         self.with_db(|db| typing::on_enter(&db, position))
297     }
298
299     /// Returns an edit which should be applied after a character was typed.
300     ///
301     /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
302     /// automatically.
303     pub fn on_char_typed(
304         &self,
305         position: FilePosition,
306         char_typed: char,
307     ) -> Cancelable<Option<SourceChange>> {
308         // Fast path to not even parse the file.
309         if !typing::TRIGGER_CHARS.contains(char_typed) {
310             return Ok(None);
311         }
312         self.with_db(|db| typing::on_char_typed(&db, position, char_typed))
313     }
314
315     /// Returns a tree representation of symbols in the file. Useful to draw a
316     /// file outline.
317     pub fn file_structure(&self, file_id: FileId) -> Cancelable<Vec<StructureNode>> {
318         self.with_db(|db| file_structure::file_structure(&db.parse(file_id).tree()))
319     }
320
321     /// Returns a list of the places in the file where type hints can be displayed.
322     pub fn inlay_hints(
323         &self,
324         file_id: FileId,
325         config: &InlayHintsConfig,
326     ) -> Cancelable<Vec<InlayHint>> {
327         self.with_db(|db| inlay_hints::inlay_hints(db, file_id, config))
328     }
329
330     /// Returns the set of folding ranges.
331     pub fn folding_ranges(&self, file_id: FileId) -> Cancelable<Vec<Fold>> {
332         self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
333     }
334
335     /// Fuzzy searches for a symbol.
336     pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
337         self.with_db(|db| {
338             symbol_index::world_symbols(db, query)
339                 .into_iter()
340                 .map(|s| s.to_nav(db))
341                 .collect::<Vec<_>>()
342         })
343     }
344
345     /// Returns the definitions from the symbol at `position`.
346     pub fn goto_definition(
347         &self,
348         position: FilePosition,
349     ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
350         self.with_db(|db| goto_definition::goto_definition(db, position))
351     }
352
353     /// Returns the impls from the symbol at `position`.
354     pub fn goto_implementation(
355         &self,
356         position: FilePosition,
357     ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
358         self.with_db(|db| goto_implementation::goto_implementation(db, position))
359     }
360
361     /// Returns the type definitions for the symbol at `position`.
362     pub fn goto_type_definition(
363         &self,
364         position: FilePosition,
365     ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
366         self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
367     }
368
369     /// Finds all usages of the reference at point.
370     pub fn find_all_refs(
371         &self,
372         position: FilePosition,
373         search_scope: Option<SearchScope>,
374     ) -> Cancelable<Option<ReferenceSearchResult>> {
375         self.with_db(|db| {
376             references::find_all_refs(&Semantics::new(db), position, search_scope).map(|it| it.info)
377         })
378     }
379
380     /// Finds all methods and free functions for the file. Does not return tests!
381     pub fn find_all_methods(&self, file_id: FileId) -> Cancelable<Vec<FileRange>> {
382         self.with_db(|db| fn_references::find_all_methods(db, file_id))
383     }
384
385     /// Returns a short text describing element at position.
386     pub fn hover(
387         &self,
388         position: FilePosition,
389         links_in_hover: bool,
390         markdown: bool,
391     ) -> Cancelable<Option<RangeInfo<HoverResult>>> {
392         self.with_db(|db| hover::hover(db, position, links_in_hover, markdown))
393     }
394
395     /// Return URL(s) for the documentation of the symbol under the cursor.
396     pub fn external_docs(
397         &self,
398         position: FilePosition,
399     ) -> Cancelable<Option<doc_links::DocumentationLink>> {
400         self.with_db(|db| doc_links::external_docs(db, &position))
401     }
402
403     /// Computes parameter information for the given call expression.
404     pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
405         self.with_db(|db| ide_db::call_info::call_info(db, position))
406     }
407
408     /// Computes call hierarchy candidates for the given file position.
409     pub fn call_hierarchy(
410         &self,
411         position: FilePosition,
412     ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
413         self.with_db(|db| call_hierarchy::call_hierarchy(db, position))
414     }
415
416     /// Computes incoming calls for the given file position.
417     pub fn incoming_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
418         self.with_db(|db| call_hierarchy::incoming_calls(db, position))
419     }
420
421     /// Computes incoming calls for the given file position.
422     pub fn outgoing_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
423         self.with_db(|db| call_hierarchy::outgoing_calls(db, position))
424     }
425
426     /// Returns a `mod name;` declaration which created the current module.
427     pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
428         self.with_db(|db| parent_module::parent_module(db, position))
429     }
430
431     /// Returns crates this file belongs too.
432     pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
433         self.with_db(|db| parent_module::crate_for(db, file_id))
434     }
435
436     /// Returns the edition of the given crate.
437     pub fn crate_edition(&self, crate_id: CrateId) -> Cancelable<Edition> {
438         self.with_db(|db| db.crate_graph()[crate_id].edition)
439     }
440
441     /// Returns the root file of the given crate.
442     pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
443         self.with_db(|db| db.crate_graph()[crate_id].root_file_id)
444     }
445
446     /// Returns the set of possible targets to run for the current file.
447     pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
448         self.with_db(|db| runnables::runnables(db, file_id))
449     }
450
451     /// Computes syntax highlighting for the given file
452     pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HlRange>> {
453         self.with_db(|db| syntax_highlighting::highlight(db, file_id, None, false))
454     }
455
456     /// Computes syntax highlighting for the given file range.
457     pub fn highlight_range(&self, frange: FileRange) -> Cancelable<Vec<HlRange>> {
458         self.with_db(|db| {
459             syntax_highlighting::highlight(db, frange.file_id, Some(frange.range), false)
460         })
461     }
462
463     /// Computes syntax highlighting for the given file.
464     pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancelable<String> {
465         self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
466     }
467
468     /// Computes completions at the given position.
469     pub fn completions(
470         &self,
471         config: &CompletionConfig,
472         position: FilePosition,
473     ) -> Cancelable<Option<Vec<CompletionItem>>> {
474         self.with_db(|db| completion::completions(db, config, position).map(Into::into))
475     }
476
477     /// Resolves additional completion data at the position given.
478     pub fn resolve_completion_edits(
479         &self,
480         config: &CompletionConfig,
481         position: FilePosition,
482         full_import_path: &str,
483         imported_name: String,
484     ) -> Cancelable<Vec<TextEdit>> {
485         Ok(self
486             .with_db(|db| {
487                 completion::resolve_completion_edits(
488                     db,
489                     config,
490                     position,
491                     full_import_path,
492                     imported_name,
493                 )
494             })?
495             .unwrap_or_default())
496     }
497
498     /// Computes assists (aka code actions aka intentions) for the given
499     /// position. If `resolve == false`, computes enough info to show the
500     /// lightbulb list in the editor, but doesn't compute actual edits, to
501     /// improve performance.
502     pub fn assists(
503         &self,
504         config: &AssistConfig,
505         resolve: bool,
506         frange: FileRange,
507     ) -> Cancelable<Vec<Assist>> {
508         self.with_db(|db| Assist::get(db, config, resolve, frange))
509     }
510
511     /// Computes the set of diagnostics for the given file.
512     pub fn diagnostics(
513         &self,
514         config: &DiagnosticsConfig,
515         file_id: FileId,
516     ) -> Cancelable<Vec<Diagnostic>> {
517         self.with_db(|db| diagnostics::diagnostics(db, config, file_id))
518     }
519
520     /// Returns the edit required to rename reference at the position to the new
521     /// name.
522     pub fn rename(
523         &self,
524         position: FilePosition,
525         new_name: &str,
526     ) -> Cancelable<Result<RangeInfo<SourceChange>, RenameError>> {
527         self.with_db(|db| references::rename::rename(db, position, new_name))
528     }
529
530     pub fn prepare_rename(
531         &self,
532         position: FilePosition,
533     ) -> Cancelable<Result<RangeInfo<()>, RenameError>> {
534         self.with_db(|db| references::rename::prepare_rename(db, position))
535     }
536
537     pub fn will_rename_file(
538         &self,
539         file_id: FileId,
540         new_name_stem: &str,
541     ) -> Cancelable<Option<SourceChange>> {
542         self.with_db(|db| references::rename::will_rename_file(db, file_id, new_name_stem))
543     }
544
545     pub fn structural_search_replace(
546         &self,
547         query: &str,
548         parse_only: bool,
549         resolve_context: FilePosition,
550         selections: Vec<FileRange>,
551     ) -> Cancelable<Result<SourceChange, SsrError>> {
552         self.with_db(|db| {
553             let rule: ssr::SsrRule = query.parse()?;
554             let mut match_finder = ssr::MatchFinder::in_context(db, resolve_context, selections);
555             match_finder.add_rule(rule)?;
556             let edits = if parse_only { Default::default() } else { match_finder.edits() };
557             Ok(SourceChange::from(edits))
558         })
559     }
560
561     /// Performs an operation on that may be Canceled.
562     fn with_db<F, T>(&self, f: F) -> Cancelable<T>
563     where
564         F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
565     {
566         self.db.catch_canceled(f)
567     }
568 }
569
570 #[test]
571 fn analysis_is_send() {
572     fn is_send<T: Send>() {}
573     is_send::<Analysis>();
574 }