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