]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/lib.rs
Improve completion of cfg attributes
[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             Default::default(),
224         );
225         change.change_file(file_id, Some(Arc::new(text)));
226         change.set_crate_graph(crate_graph);
227         host.apply_change(change);
228         (host.analysis(), file_id)
229     }
230
231     /// Debug info about the current state of the analysis.
232     pub fn status(&self, file_id: Option<FileId>) -> Cancellable<String> {
233         self.with_db(|db| status::status(&*db, file_id))
234     }
235
236     pub fn prime_caches<F>(&self, cb: F) -> Cancellable<()>
237     where
238         F: Fn(PrimeCachesProgress) + Sync + std::panic::UnwindSafe,
239     {
240         self.with_db(move |db| prime_caches::prime_caches(db, &cb))
241     }
242
243     /// Gets the text of the source file.
244     pub fn file_text(&self, file_id: FileId) -> Cancellable<Arc<String>> {
245         self.with_db(|db| db.file_text(file_id))
246     }
247
248     /// Gets the syntax tree of the file.
249     pub fn parse(&self, file_id: FileId) -> Cancellable<SourceFile> {
250         self.with_db(|db| db.parse(file_id).tree())
251     }
252
253     /// Returns true if this file belongs to an immutable library.
254     pub fn is_library_file(&self, file_id: FileId) -> Cancellable<bool> {
255         use ide_db::base_db::SourceDatabaseExt;
256         self.with_db(|db| db.source_root(db.file_source_root(file_id)).is_library)
257     }
258
259     /// Gets the file's `LineIndex`: data structure to convert between absolute
260     /// offsets and line/column representation.
261     pub fn file_line_index(&self, file_id: FileId) -> Cancellable<Arc<LineIndex>> {
262         self.with_db(|db| db.line_index(file_id))
263     }
264
265     /// Selects the next syntactic nodes encompassing the range.
266     pub fn extend_selection(&self, frange: FileRange) -> Cancellable<TextRange> {
267         self.with_db(|db| extend_selection::extend_selection(db, frange))
268     }
269
270     /// Returns position of the matching brace (all types of braces are
271     /// supported).
272     pub fn matching_brace(&self, position: FilePosition) -> Cancellable<Option<TextSize>> {
273         self.with_db(|db| {
274             let parse = db.parse(position.file_id);
275             let file = parse.tree();
276             matching_brace::matching_brace(&file, position.offset)
277         })
278     }
279
280     /// Returns a syntax tree represented as `String`, for debug purposes.
281     // FIXME: use a better name here.
282     pub fn syntax_tree(
283         &self,
284         file_id: FileId,
285         text_range: Option<TextRange>,
286     ) -> Cancellable<String> {
287         self.with_db(|db| syntax_tree::syntax_tree(db, file_id, text_range))
288     }
289
290     pub fn view_hir(&self, position: FilePosition) -> Cancellable<String> {
291         self.with_db(|db| view_hir::view_hir(db, position))
292     }
293
294     pub fn view_item_tree(&self, file_id: FileId) -> Cancellable<String> {
295         self.with_db(|db| view_item_tree::view_item_tree(db, file_id))
296     }
297
298     /// Renders the crate graph to GraphViz "dot" syntax.
299     pub fn view_crate_graph(&self) -> Cancellable<Result<String, String>> {
300         self.with_db(|db| view_crate_graph::view_crate_graph(db))
301     }
302
303     pub fn expand_macro(&self, position: FilePosition) -> Cancellable<Option<ExpandedMacro>> {
304         self.with_db(|db| expand_macro::expand_macro(db, position))
305     }
306
307     /// Returns an edit to remove all newlines in the range, cleaning up minor
308     /// stuff like trailing commas.
309     pub fn join_lines(&self, frange: FileRange) -> Cancellable<TextEdit> {
310         self.with_db(|db| {
311             let parse = db.parse(frange.file_id);
312             join_lines::join_lines(&parse.tree(), frange.range)
313         })
314     }
315
316     /// Returns an edit which should be applied when opening a new line, fixing
317     /// up minor stuff like continuing the comment.
318     /// The edit will be a snippet (with `$0`).
319     pub fn on_enter(&self, position: FilePosition) -> Cancellable<Option<TextEdit>> {
320         self.with_db(|db| typing::on_enter(db, position))
321     }
322
323     /// Returns an edit which should be applied after a character was typed.
324     ///
325     /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
326     /// automatically.
327     pub fn on_char_typed(
328         &self,
329         position: FilePosition,
330         char_typed: char,
331     ) -> Cancellable<Option<SourceChange>> {
332         // Fast path to not even parse the file.
333         if !typing::TRIGGER_CHARS.contains(char_typed) {
334             return Ok(None);
335         }
336         self.with_db(|db| typing::on_char_typed(db, position, char_typed))
337     }
338
339     /// Returns a tree representation of symbols in the file. Useful to draw a
340     /// file outline.
341     pub fn file_structure(&self, file_id: FileId) -> Cancellable<Vec<StructureNode>> {
342         self.with_db(|db| file_structure::file_structure(&db.parse(file_id).tree()))
343     }
344
345     /// Returns a list of the places in the file where type hints can be displayed.
346     pub fn inlay_hints(
347         &self,
348         file_id: FileId,
349         config: &InlayHintsConfig,
350     ) -> Cancellable<Vec<InlayHint>> {
351         self.with_db(|db| inlay_hints::inlay_hints(db, file_id, config))
352     }
353
354     /// Returns the set of folding ranges.
355     pub fn folding_ranges(&self, file_id: FileId) -> Cancellable<Vec<Fold>> {
356         self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
357     }
358
359     /// Fuzzy searches for a symbol.
360     pub fn symbol_search(&self, query: Query) -> Cancellable<Vec<NavigationTarget>> {
361         self.with_db(|db| {
362             symbol_index::world_symbols(db, query)
363                 .into_iter()
364                 .map(|s| s.to_nav(db))
365                 .collect::<Vec<_>>()
366         })
367     }
368
369     /// Returns the definitions from the symbol at `position`.
370     pub fn goto_definition(
371         &self,
372         position: FilePosition,
373     ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
374         self.with_db(|db| goto_definition::goto_definition(db, position))
375     }
376
377     /// Returns the impls from the symbol at `position`.
378     pub fn goto_implementation(
379         &self,
380         position: FilePosition,
381     ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
382         self.with_db(|db| goto_implementation::goto_implementation(db, position))
383     }
384
385     /// Returns the type definitions for the symbol at `position`.
386     pub fn goto_type_definition(
387         &self,
388         position: FilePosition,
389     ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
390         self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
391     }
392
393     /// Finds all usages of the reference at point.
394     pub fn find_all_refs(
395         &self,
396         position: FilePosition,
397         search_scope: Option<SearchScope>,
398     ) -> Cancellable<Option<ReferenceSearchResult>> {
399         self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, search_scope))
400     }
401
402     /// Finds all methods and free functions for the file. Does not return tests!
403     pub fn find_all_methods(&self, file_id: FileId) -> Cancellable<Vec<FileRange>> {
404         self.with_db(|db| fn_references::find_all_methods(db, file_id))
405     }
406
407     /// Returns a short text describing element at position.
408     pub fn hover(
409         &self,
410         position: FilePosition,
411         links_in_hover: bool,
412         documentation: bool,
413         markdown: bool,
414     ) -> Cancellable<Option<RangeInfo<HoverResult>>> {
415         self.with_db(|db| hover::hover(db, position, links_in_hover, documentation, markdown))
416     }
417
418     /// Return URL(s) for the documentation of the symbol under the cursor.
419     pub fn external_docs(
420         &self,
421         position: FilePosition,
422     ) -> Cancellable<Option<doc_links::DocumentationLink>> {
423         self.with_db(|db| doc_links::external_docs(db, &position))
424     }
425
426     /// Computes parameter information for the given call expression.
427     pub fn call_info(&self, position: FilePosition) -> Cancellable<Option<CallInfo>> {
428         self.with_db(|db| ide_db::call_info::call_info(db, position))
429     }
430
431     /// Computes call hierarchy candidates for the given file position.
432     pub fn call_hierarchy(
433         &self,
434         position: FilePosition,
435     ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
436         self.with_db(|db| call_hierarchy::call_hierarchy(db, position))
437     }
438
439     /// Computes incoming calls for the given file position.
440     pub fn incoming_calls(&self, position: FilePosition) -> Cancellable<Option<Vec<CallItem>>> {
441         self.with_db(|db| call_hierarchy::incoming_calls(db, position))
442     }
443
444     /// Computes incoming calls for the given file position.
445     pub fn outgoing_calls(&self, position: FilePosition) -> Cancellable<Option<Vec<CallItem>>> {
446         self.with_db(|db| call_hierarchy::outgoing_calls(db, position))
447     }
448
449     /// Returns a `mod name;` declaration which created the current module.
450     pub fn parent_module(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
451         self.with_db(|db| parent_module::parent_module(db, position))
452     }
453
454     /// Returns crates this file belongs too.
455     pub fn crate_for(&self, file_id: FileId) -> Cancellable<Vec<CrateId>> {
456         self.with_db(|db| parent_module::crate_for(db, file_id))
457     }
458
459     /// Returns the edition of the given crate.
460     pub fn crate_edition(&self, crate_id: CrateId) -> Cancellable<Edition> {
461         self.with_db(|db| db.crate_graph()[crate_id].edition)
462     }
463
464     /// Returns the root file of the given crate.
465     pub fn crate_root(&self, crate_id: CrateId) -> Cancellable<FileId> {
466         self.with_db(|db| db.crate_graph()[crate_id].root_file_id)
467     }
468
469     /// Returns the set of possible targets to run for the current file.
470     pub fn runnables(&self, file_id: FileId) -> Cancellable<Vec<Runnable>> {
471         self.with_db(|db| runnables::runnables(db, file_id))
472     }
473
474     /// Returns the set of tests for the given file position.
475     pub fn related_tests(
476         &self,
477         position: FilePosition,
478         search_scope: Option<SearchScope>,
479     ) -> Cancellable<Vec<Runnable>> {
480         self.with_db(|db| runnables::related_tests(db, position, search_scope))
481     }
482
483     /// Computes syntax highlighting for the given file
484     pub fn highlight(&self, file_id: FileId) -> Cancellable<Vec<HlRange>> {
485         self.with_db(|db| syntax_highlighting::highlight(db, file_id, None, false))
486     }
487
488     /// Computes syntax highlighting for the given file range.
489     pub fn highlight_range(&self, frange: FileRange) -> Cancellable<Vec<HlRange>> {
490         self.with_db(|db| {
491             syntax_highlighting::highlight(db, frange.file_id, Some(frange.range), false)
492         })
493     }
494
495     /// Computes syntax highlighting for the given file.
496     pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancellable<String> {
497         self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
498     }
499
500     /// Computes completions at the given position.
501     pub fn completions(
502         &self,
503         config: &CompletionConfig,
504         position: FilePosition,
505     ) -> Cancellable<Option<Vec<CompletionItem>>> {
506         self.with_db(|db| ide_completion::completions(db, config, position).map(Into::into))
507     }
508
509     /// Resolves additional completion data at the position given.
510     pub fn resolve_completion_edits(
511         &self,
512         config: &CompletionConfig,
513         position: FilePosition,
514         full_import_path: &str,
515         imported_name: String,
516     ) -> Cancellable<Vec<TextEdit>> {
517         Ok(self
518             .with_db(|db| {
519                 ide_completion::resolve_completion_edits(
520                     db,
521                     config,
522                     position,
523                     full_import_path,
524                     imported_name,
525                 )
526             })?
527             .unwrap_or_default())
528     }
529
530     /// Computes assists (aka code actions aka intentions) for the given
531     /// position. If `resolve == false`, computes enough info to show the
532     /// lightbulb list in the editor, but doesn't compute actual edits, to
533     /// improve performance.
534     pub fn assists(
535         &self,
536         config: &AssistConfig,
537         resolve: AssistResolveStrategy,
538         frange: FileRange,
539     ) -> Cancellable<Vec<Assist>> {
540         self.with_db(|db| {
541             let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
542             let mut acc = ide_assists::assists(db, config, resolve, frange);
543             acc.extend(ssr_assists.into_iter());
544             acc
545         })
546     }
547
548     /// Computes the set of diagnostics for the given file.
549     pub fn diagnostics(
550         &self,
551         config: &DiagnosticsConfig,
552         resolve: AssistResolveStrategy,
553         file_id: FileId,
554     ) -> Cancellable<Vec<Diagnostic>> {
555         self.with_db(|db| ide_diagnostics::diagnostics(db, config, &resolve, file_id))
556     }
557
558     /// Convenience function to return assists + quick fixes for diagnostics
559     pub fn assists_with_fixes(
560         &self,
561         assist_config: &AssistConfig,
562         diagnostics_config: &DiagnosticsConfig,
563         resolve: AssistResolveStrategy,
564         frange: FileRange,
565     ) -> Cancellable<Vec<Assist>> {
566         let include_fixes = match &assist_config.allowed {
567             Some(it) => it.iter().any(|&it| it == AssistKind::None || it == AssistKind::QuickFix),
568             None => true,
569         };
570
571         self.with_db(|db| {
572             let diagnostic_assists = if include_fixes {
573                 ide_diagnostics::diagnostics(db, diagnostics_config, &resolve, frange.file_id)
574                     .into_iter()
575                     .flat_map(|it| it.fixes.unwrap_or_default())
576                     .filter(|it| it.target.intersect(frange.range).is_some())
577                     .collect()
578             } else {
579                 Vec::new()
580             };
581             let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
582             let assists = ide_assists::assists(db, assist_config, resolve, frange);
583
584             let mut res = diagnostic_assists;
585             res.extend(ssr_assists.into_iter());
586             res.extend(assists.into_iter());
587
588             res
589         })
590     }
591
592     /// Returns the edit required to rename reference at the position to the new
593     /// name.
594     pub fn rename(
595         &self,
596         position: FilePosition,
597         new_name: &str,
598     ) -> Cancellable<Result<SourceChange, RenameError>> {
599         self.with_db(|db| rename::rename(db, position, new_name))
600     }
601
602     pub fn prepare_rename(
603         &self,
604         position: FilePosition,
605     ) -> Cancellable<Result<RangeInfo<()>, RenameError>> {
606         self.with_db(|db| rename::prepare_rename(db, position))
607     }
608
609     pub fn will_rename_file(
610         &self,
611         file_id: FileId,
612         new_name_stem: &str,
613     ) -> Cancellable<Option<SourceChange>> {
614         self.with_db(|db| rename::will_rename_file(db, file_id, new_name_stem))
615     }
616
617     pub fn structural_search_replace(
618         &self,
619         query: &str,
620         parse_only: bool,
621         resolve_context: FilePosition,
622         selections: Vec<FileRange>,
623     ) -> Cancellable<Result<SourceChange, SsrError>> {
624         self.with_db(|db| {
625             let rule: ide_ssr::SsrRule = query.parse()?;
626             let mut match_finder =
627                 ide_ssr::MatchFinder::in_context(db, resolve_context, selections);
628             match_finder.add_rule(rule)?;
629             let edits = if parse_only { Default::default() } else { match_finder.edits() };
630             Ok(SourceChange::from(edits))
631         })
632     }
633
634     pub fn annotations(
635         &self,
636         file_id: FileId,
637         config: AnnotationConfig,
638     ) -> Cancellable<Vec<Annotation>> {
639         self.with_db(|db| annotations::annotations(db, file_id, config))
640     }
641
642     pub fn resolve_annotation(&self, annotation: Annotation) -> Cancellable<Annotation> {
643         self.with_db(|db| annotations::resolve_annotation(db, annotation))
644     }
645
646     pub fn move_item(
647         &self,
648         range: FileRange,
649         direction: Direction,
650     ) -> Cancellable<Option<TextEdit>> {
651         self.with_db(|db| move_item::move_item(db, range, direction))
652     }
653
654     /// Performs an operation on the database that may be canceled.
655     ///
656     /// rust-analyzer needs to be able to answer semantic questions about the
657     /// code while the code is being modified. A common problem is that a
658     /// long-running query is being calculated when a new change arrives.
659     ///
660     /// We can't just apply the change immediately: this will cause the pending
661     /// query to see inconsistent state (it will observe an absence of
662     /// repeatable read). So what we do is we **cancel** all pending queries
663     /// before applying the change.
664     ///
665     /// Salsa implements cancelation by unwinding with a special value and
666     /// catching it on the API boundary.
667     fn with_db<F, T>(&self, f: F) -> Cancellable<T>
668     where
669         F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
670     {
671         Cancelled::catch(|| f(&self.db))
672     }
673 }
674
675 #[test]
676 fn analysis_is_send() {
677     fn is_send<T: Send>() {}
678     is_send::<Analysis>();
679 }