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