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