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