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