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