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