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