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