1#![cfg_attr(feature = "in-rust-tree", feature(rustc_private))]
13#![recursion_limit = "128"]
14
15#[cfg(test)]
16mod fixture;
17
18mod markup;
19mod navigation_target;
20
21mod annotations;
22mod call_hierarchy;
23mod child_modules;
24mod doc_links;
25mod expand_macro;
26mod extend_selection;
27mod fetch_crates;
28mod file_structure;
29mod folding_ranges;
30mod goto_declaration;
31mod goto_definition;
32mod goto_implementation;
33mod goto_type_definition;
34mod highlight_related;
35mod hover;
36mod inlay_hints;
37mod interpret;
38mod join_lines;
39mod markdown_remove;
40mod matching_brace;
41mod moniker;
42mod move_item;
43mod parent_module;
44mod references;
45mod rename;
46mod runnables;
47mod signature_help;
48mod ssr;
49mod static_index;
50mod status;
51mod syntax_highlighting;
52mod test_explorer;
53mod typing;
54mod view_crate_graph;
55mod view_hir;
56mod view_item_tree;
57mod view_memory_layout;
58mod view_mir;
59mod view_syntax_tree;
60
61use std::panic::{AssertUnwindSafe, UnwindSafe};
62
63use cfg::CfgOptions;
64use fetch_crates::CrateInfo;
65use hir::{ChangeWithProcMacros, EditionedFileId, crate_def_map, sym};
66use ide_db::ra_fixture::RaFixtureAnalysis;
67use ide_db::{
68 FxHashMap, FxIndexSet, LineIndexDatabase,
69 base_db::{
70 CrateOrigin, CrateWorkspaceData, Env, FileSet, RootQueryDb, SourceDatabase, VfsPath,
71 salsa::{Cancelled, Database},
72 },
73 prime_caches, symbol_index,
74};
75use macros::UpmapFromRaFixture;
76use syntax::{AstNode, SourceFile, ast};
77use triomphe::Arc;
78use view_memory_layout::{RecursiveMemoryLayout, view_memory_layout};
79
80use crate::navigation_target::ToNav;
81
82pub use crate::{
83 annotations::{Annotation, AnnotationConfig, AnnotationKind, AnnotationLocation},
84 call_hierarchy::{CallHierarchyConfig, CallItem},
85 expand_macro::ExpandedMacro,
86 file_structure::{FileStructureConfig, StructureNode, StructureNodeKind},
87 folding_ranges::{Fold, FoldKind},
88 goto_definition::GotoDefinitionConfig,
89 goto_implementation::GotoImplementationConfig,
90 highlight_related::{HighlightRelatedConfig, HighlightedRange},
91 hover::{
92 HoverAction, HoverConfig, HoverDocFormat, HoverGotoTypeData, HoverResult,
93 MemoryLayoutHoverConfig, MemoryLayoutHoverRenderKind, SubstTyLen,
94 },
95 inlay_hints::{
96 AdjustmentHints, AdjustmentHintsMode, ClosureReturnTypeHints, DiscriminantHints,
97 GenericParameterHints, InlayFieldsToResolve, InlayHint, InlayHintLabel, InlayHintLabelPart,
98 InlayHintPosition, InlayHintsConfig, InlayKind, InlayTooltip, LazyProperty,
99 LifetimeElisionHints,
100 },
101 join_lines::JoinLinesConfig,
102 markup::Markup,
103 moniker::{
104 Moniker, MonikerDescriptorKind, MonikerIdentifier, MonikerKind, MonikerResult,
105 PackageInformation, SymbolInformationKind,
106 },
107 move_item::Direction,
108 navigation_target::{NavigationTarget, TryToNav, UpmappingResult},
109 references::{FindAllRefsConfig, ReferenceSearchResult},
110 rename::{RenameConfig, RenameError},
111 runnables::{Runnable, RunnableKind, TestId, UpdateTest},
112 signature_help::SignatureHelp,
113 static_index::{
114 StaticIndex, StaticIndexedFile, TokenId, TokenStaticData, VendoredLibrariesConfig,
115 },
116 syntax_highlighting::{
117 HighlightConfig, HlRange,
118 tags::{Highlight, HlMod, HlMods, HlOperator, HlPunct, HlTag},
119 },
120 test_explorer::{TestItem, TestItemKind},
121};
122pub use hir::Semantics;
123pub use ide_assists::{
124 Assist, AssistConfig, AssistId, AssistKind, AssistResolveStrategy, SingleResolve,
125};
126pub use ide_completion::{
127 CallableSnippets, CompletionConfig, CompletionFieldsToResolve, CompletionItem,
128 CompletionItemKind, CompletionItemRefMode, CompletionRelevance, Snippet, SnippetScope,
129};
130pub use ide_db::{
131 FileId, FilePosition, FileRange, RootDatabase, Severity, SymbolKind,
132 assists::ExprFillDefaultMode,
133 base_db::{Crate, CrateGraphBuilder, FileChange, SourceRoot, SourceRootId},
134 documentation::Documentation,
135 label::Label,
136 line_index::{LineCol, LineIndex},
137 prime_caches::ParallelPrimeCachesProgress,
138 ra_fixture::RaFixtureConfig,
139 search::{ReferenceCategory, SearchScope},
140 source_change::{FileSystemEdit, SnippetEdit, SourceChange},
141 symbol_index::Query,
142 text_edit::{Indel, TextEdit},
143};
144pub use ide_diagnostics::{Diagnostic, DiagnosticCode, DiagnosticsConfig};
145pub use ide_ssr::SsrError;
146pub use span::Edition;
147pub use syntax::{TextRange, TextSize};
148
149pub type Cancellable<T> = Result<T, Cancelled>;
150
151#[derive(Debug, UpmapFromRaFixture)]
153pub struct RangeInfo<T> {
154 pub range: TextRange,
155 pub info: T,
156}
157
158impl<T> RangeInfo<T> {
159 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
160 RangeInfo { range, info }
161 }
162}
163
164#[derive(Debug)]
166pub struct AnalysisHost {
167 db: RootDatabase,
168}
169
170impl AnalysisHost {
171 pub fn new(lru_capacity: Option<u16>) -> AnalysisHost {
172 AnalysisHost { db: RootDatabase::new(lru_capacity) }
173 }
174
175 pub fn with_database(db: RootDatabase) -> AnalysisHost {
176 AnalysisHost { db }
177 }
178
179 pub fn update_lru_capacity(&mut self, lru_capacity: Option<u16>) {
180 self.db.update_base_query_lru_capacities(lru_capacity);
181 }
182
183 pub fn update_lru_capacities(&mut self, lru_capacities: &FxHashMap<Box<str>, u16>) {
184 self.db.update_lru_capacities(lru_capacities);
185 }
186
187 pub fn analysis(&self) -> Analysis {
190 Analysis { db: self.db.clone() }
191 }
192
193 pub fn apply_change(&mut self, change: ChangeWithProcMacros) {
196 self.db.apply_change(change);
197 }
198
199 pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes, usize)> {
201 self.db.per_query_memory_usage()
202 }
203 pub fn trigger_cancellation(&mut self) {
204 self.db.trigger_cancellation();
205 }
206 pub fn trigger_garbage_collection(&mut self) {
207 self.db.trigger_lru_eviction();
208 unsafe { hir::collect_ty_garbage() };
210 }
211 pub fn raw_database(&self) -> &RootDatabase {
212 &self.db
213 }
214 pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
215 &mut self.db
216 }
217}
218
219impl Default for AnalysisHost {
220 fn default() -> AnalysisHost {
221 AnalysisHost::new(None)
222 }
223}
224
225#[derive(Debug)]
230pub struct Analysis {
231 db: RootDatabase,
232}
233
234impl Analysis {
241 pub fn from_single_file(text: String) -> (Analysis, FileId) {
245 let mut host = AnalysisHost::default();
246 let file_id = FileId::from_raw(0);
247 let mut file_set = FileSet::default();
248 file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_owned()));
249 let source_root = SourceRoot::new_local(file_set);
250
251 let mut change = ChangeWithProcMacros::default();
252 change.set_roots(vec![source_root]);
253 let mut crate_graph = CrateGraphBuilder::default();
254 let mut cfg_options = CfgOptions::default();
257
258 let proc_macro_cwd = Arc::new(
260 TryFrom::try_from(&*std::env::current_dir().unwrap().as_path().to_string_lossy())
261 .unwrap(),
262 );
263 let crate_attrs = Vec::new();
264 cfg_options.insert_atom(sym::test);
265 crate_graph.add_crate_root(
266 file_id,
267 Edition::CURRENT,
268 None,
269 None,
270 cfg_options,
271 None,
272 Env::default(),
273 CrateOrigin::Local { repo: None, name: None },
274 crate_attrs,
275 false,
276 proc_macro_cwd,
277 Arc::new(CrateWorkspaceData {
278 target: Err("fixture has no layout".into()),
279 toolchain: None,
280 }),
281 );
282 change.change_file(file_id, Some(text));
283 change.set_crate_graph(crate_graph);
284
285 host.apply_change(change);
286 (host.analysis(), file_id)
287 }
288
289 pub(crate) fn from_ra_fixture(
290 sema: &Semantics<'_, RootDatabase>,
291 literal: ast::String,
292 expanded: &ast::String,
293 config: &RaFixtureConfig<'_>,
294 ) -> Option<(Analysis, RaFixtureAnalysis)> {
295 Self::from_ra_fixture_with_on_cursor(sema, literal, expanded, config, &mut |_| {})
296 }
297
298 pub(crate) fn from_ra_fixture_with_on_cursor(
300 sema: &Semantics<'_, RootDatabase>,
301 literal: ast::String,
302 expanded: &ast::String,
303 config: &RaFixtureConfig<'_>,
304 on_cursor: &mut dyn FnMut(TextRange),
305 ) -> Option<(Analysis, RaFixtureAnalysis)> {
306 let analysis =
307 RaFixtureAnalysis::analyze_ra_fixture(sema, literal, expanded, config, on_cursor)?;
308 Some((Analysis { db: analysis.db.clone() }, analysis))
309 }
310
311 pub fn status(&self, file_id: Option<FileId>) -> Cancellable<String> {
313 self.with_db(|db| status::status(db, file_id))
314 }
315
316 pub fn source_root_id(&self, file_id: FileId) -> Cancellable<SourceRootId> {
317 self.with_db(|db| db.file_source_root(file_id).source_root_id(db))
318 }
319
320 pub fn is_local_source_root(&self, source_root_id: SourceRootId) -> Cancellable<bool> {
321 self.with_db(|db| {
322 let sr = db.source_root(source_root_id).source_root(db);
323 !sr.is_library
324 })
325 }
326
327 pub fn parallel_prime_caches<F>(&self, num_worker_threads: usize, cb: F) -> Cancellable<()>
328 where
329 F: Fn(ParallelPrimeCachesProgress) + Sync + std::panic::UnwindSafe,
330 {
331 self.with_db(move |db| prime_caches::parallel_prime_caches(db, num_worker_threads, &cb))
332 }
333
334 pub fn file_text(&self, file_id: FileId) -> Cancellable<Arc<str>> {
336 self.with_db(|db| SourceDatabase::file_text(db, file_id).text(db).clone())
337 }
338
339 pub fn parse(&self, file_id: FileId) -> Cancellable<SourceFile> {
341 self.with_db(|db| {
343 let editioned_file_id_wrapper = EditionedFileId::current_edition(&self.db, file_id);
344
345 db.parse(editioned_file_id_wrapper).tree()
346 })
347 }
348
349 pub fn is_library_file(&self, file_id: FileId) -> Cancellable<bool> {
351 self.with_db(|db| {
352 let source_root = db.file_source_root(file_id).source_root_id(db);
353 db.source_root(source_root).source_root(db).is_library
354 })
355 }
356
357 pub fn file_line_index(&self, file_id: FileId) -> Cancellable<Arc<LineIndex>> {
360 self.with_db(|db| db.line_index(file_id))
361 }
362
363 pub fn extend_selection(&self, frange: FileRange) -> Cancellable<TextRange> {
365 self.with_db(|db| extend_selection::extend_selection(db, frange))
366 }
367
368 pub fn matching_brace(&self, position: FilePosition) -> Cancellable<Option<TextSize>> {
371 self.with_db(|db| {
372 let file_id = EditionedFileId::current_edition(&self.db, position.file_id);
373 let parse = db.parse(file_id);
374 let file = parse.tree();
375 matching_brace::matching_brace(&file, position.offset)
376 })
377 }
378
379 pub fn view_syntax_tree(&self, file_id: FileId) -> Cancellable<String> {
380 self.with_db(|db| view_syntax_tree::view_syntax_tree(db, file_id))
381 }
382
383 pub fn view_hir(&self, position: FilePosition) -> Cancellable<String> {
384 self.with_db(|db| view_hir::view_hir(db, position))
385 }
386
387 pub fn view_mir(&self, position: FilePosition) -> Cancellable<String> {
388 self.with_db(|db| view_mir::view_mir(db, position))
389 }
390
391 pub fn interpret_function(&self, position: FilePosition) -> Cancellable<String> {
392 self.with_db(|db| interpret::interpret(db, position))
393 }
394
395 pub fn view_item_tree(&self, file_id: FileId) -> Cancellable<String> {
396 self.with_db(|db| view_item_tree::view_item_tree(db, file_id))
397 }
398
399 pub fn discover_test_roots(&self) -> Cancellable<Vec<TestItem>> {
400 self.with_db(test_explorer::discover_test_roots)
401 }
402
403 pub fn discover_tests_in_crate_by_test_id(&self, crate_id: &str) -> Cancellable<Vec<TestItem>> {
404 self.with_db(|db| test_explorer::discover_tests_in_crate_by_test_id(db, crate_id))
405 }
406
407 pub fn discover_tests_in_crate(&self, crate_id: Crate) -> Cancellable<Vec<TestItem>> {
408 self.with_db(|db| test_explorer::discover_tests_in_crate(db, crate_id))
409 }
410
411 pub fn discover_tests_in_file(&self, file_id: FileId) -> Cancellable<Vec<TestItem>> {
412 self.with_db(|db| test_explorer::discover_tests_in_file(db, file_id))
413 }
414
415 pub fn view_crate_graph(&self, full: bool) -> Cancellable<Result<String, String>> {
417 self.with_db(|db| view_crate_graph::view_crate_graph(db, full))
418 }
419
420 pub fn fetch_crates(&self) -> Cancellable<FxIndexSet<CrateInfo>> {
421 self.with_db(fetch_crates::fetch_crates)
422 }
423
424 pub fn expand_macro(&self, position: FilePosition) -> Cancellable<Option<ExpandedMacro>> {
425 self.with_db(|db| expand_macro::expand_macro(db, position))
426 }
427
428 pub fn join_lines(&self, config: &JoinLinesConfig, frange: FileRange) -> Cancellable<TextEdit> {
431 self.with_db(|db| {
432 let editioned_file_id_wrapper =
433 EditionedFileId::current_edition(&self.db, frange.file_id);
434 let parse = db.parse(editioned_file_id_wrapper);
435 join_lines::join_lines(config, &parse.tree(), frange.range)
436 })
437 }
438
439 pub fn on_enter(&self, position: FilePosition) -> Cancellable<Option<TextEdit>> {
443 self.with_db(|db| typing::on_enter(db, position))
444 }
445
446 pub const SUPPORTED_TRIGGER_CHARS: &[char] = typing::TRIGGER_CHARS;
447
448 pub fn on_char_typed(
453 &self,
454 position: FilePosition,
455 char_typed: char,
456 ) -> Cancellable<Option<SourceChange>> {
457 if !typing::TRIGGER_CHARS.contains(&char_typed) {
459 return Ok(None);
460 }
461
462 self.with_db(|db| typing::on_char_typed(db, position, char_typed))
463 }
464
465 pub fn file_structure(
468 &self,
469 config: &FileStructureConfig,
470 file_id: FileId,
471 ) -> Cancellable<Vec<StructureNode>> {
472 self.with_db(|db| {
474 let editioned_file_id_wrapper = EditionedFileId::current_edition(&self.db, file_id);
475 let source_file = db.parse(editioned_file_id_wrapper).tree();
476 file_structure::file_structure(&source_file, config)
477 })
478 }
479
480 pub fn inlay_hints(
482 &self,
483 config: &InlayHintsConfig<'_>,
484 file_id: FileId,
485 range: Option<TextRange>,
486 ) -> Cancellable<Vec<InlayHint>> {
487 self.with_db(|db| inlay_hints::inlay_hints(db, file_id, range, config))
488 }
489 pub fn inlay_hints_resolve(
490 &self,
491 config: &InlayHintsConfig<'_>,
492 file_id: FileId,
493 resolve_range: TextRange,
494 hash: u64,
495 hasher: impl Fn(&InlayHint) -> u64 + Send + UnwindSafe,
496 ) -> Cancellable<Option<InlayHint>> {
497 self.with_db(|db| {
498 inlay_hints::inlay_hints_resolve(db, file_id, resolve_range, hash, config, hasher)
499 })
500 }
501
502 pub fn folding_ranges(&self, file_id: FileId) -> Cancellable<Vec<Fold>> {
504 self.with_db(|db| {
505 let editioned_file_id_wrapper = EditionedFileId::current_edition(&self.db, file_id);
506
507 folding_ranges::folding_ranges(&db.parse(editioned_file_id_wrapper).tree())
508 })
509 }
510
511 pub fn symbol_search(&self, query: Query, limit: usize) -> Cancellable<Vec<NavigationTarget>> {
513 Cancelled::catch(|| {
516 let symbols = symbol_index::world_symbols(&self.db, query);
517 hir::attach_db(&self.db, || {
518 symbols
519 .into_iter()
520 .filter_map(|s| s.try_to_nav(&Semantics::new(&self.db)))
521 .take(limit)
522 .map(UpmappingResult::call_site)
523 .collect::<Vec<_>>()
524 })
525 })
526 }
527
528 pub fn goto_definition(
530 &self,
531 position: FilePosition,
532 config: &GotoDefinitionConfig<'_>,
533 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
534 self.with_db(|db| goto_definition::goto_definition(db, position, config))
535 }
536
537 pub fn goto_declaration(
539 &self,
540 position: FilePosition,
541 config: &GotoDefinitionConfig<'_>,
542 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
543 self.with_db(|db| goto_declaration::goto_declaration(db, position, config))
544 }
545
546 pub fn goto_implementation(
548 &self,
549 config: &GotoImplementationConfig,
550 position: FilePosition,
551 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
552 self.with_db(|db| goto_implementation::goto_implementation(db, config, position))
553 }
554
555 pub fn goto_type_definition(
557 &self,
558 position: FilePosition,
559 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
560 self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
561 }
562
563 pub fn find_all_refs(
564 &self,
565 position: FilePosition,
566 config: &FindAllRefsConfig<'_>,
567 ) -> Cancellable<Option<Vec<ReferenceSearchResult>>> {
568 let config = AssertUnwindSafe(config);
569 self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, &config))
570 }
571
572 pub fn hover(
574 &self,
575 config: &HoverConfig<'_>,
576 range: FileRange,
577 ) -> Cancellable<Option<RangeInfo<HoverResult>>> {
578 self.with_db(|db| hover::hover(db, range, config))
579 }
580
581 pub fn moniker(
583 &self,
584 position: FilePosition,
585 ) -> Cancellable<Option<RangeInfo<Vec<moniker::MonikerResult>>>> {
586 self.with_db(|db| moniker::moniker(db, position))
587 }
588
589 pub fn external_docs(
594 &self,
595 position: FilePosition,
596 target_dir: Option<&str>,
597 sysroot: Option<&str>,
598 ) -> Cancellable<doc_links::DocumentationLinks> {
599 self.with_db(|db| {
600 doc_links::external_docs(db, position, target_dir, sysroot).unwrap_or_default()
601 })
602 }
603
604 pub fn signature_help(&self, position: FilePosition) -> Cancellable<Option<SignatureHelp>> {
606 self.with_db(|db| signature_help::signature_help(db, position))
607 }
608
609 pub fn call_hierarchy(
611 &self,
612 position: FilePosition,
613 config: &CallHierarchyConfig<'_>,
614 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
615 self.with_db(|db| call_hierarchy::call_hierarchy(db, position, config))
616 }
617
618 pub fn incoming_calls(
620 &self,
621 config: &CallHierarchyConfig<'_>,
622 position: FilePosition,
623 ) -> Cancellable<Option<Vec<CallItem>>> {
624 self.with_db(|db| call_hierarchy::incoming_calls(db, config, position))
625 }
626
627 pub fn outgoing_calls(
629 &self,
630 config: &CallHierarchyConfig<'_>,
631 position: FilePosition,
632 ) -> Cancellable<Option<Vec<CallItem>>> {
633 self.with_db(|db| call_hierarchy::outgoing_calls(db, config, position))
634 }
635
636 pub fn parent_module(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
638 self.with_db(|db| parent_module::parent_module(db, position))
639 }
640
641 pub fn child_modules(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
643 self.with_db(|db| child_modules::child_modules(db, position))
644 }
645
646 pub fn crates_for(&self, file_id: FileId) -> Cancellable<Vec<Crate>> {
648 self.with_db(|db| parent_module::crates_for(db, file_id))
649 }
650
651 pub fn transitive_rev_deps(&self, crate_id: Crate) -> Cancellable<Vec<Crate>> {
653 self.with_db(|db| Vec::from_iter(crate_id.transitive_rev_deps(db)))
654 }
655
656 pub fn relevant_crates_for(&self, file_id: FileId) -> Cancellable<Vec<Crate>> {
658 self.with_db(|db| db.relevant_crates(file_id).iter().copied().collect())
659 }
660
661 pub fn crate_edition(&self, crate_id: Crate) -> Cancellable<Edition> {
663 self.with_db(|db| crate_id.data(db).edition)
664 }
665
666 pub fn is_proc_macro_crate(&self, crate_id: Crate) -> Cancellable<bool> {
668 self.with_db(|db| crate_id.data(db).is_proc_macro)
669 }
670
671 pub fn is_crate_no_std(&self, crate_id: Crate) -> Cancellable<bool> {
673 self.with_db(|db| crate_def_map(db, crate_id).is_no_std())
674 }
675
676 pub fn crate_root(&self, crate_id: Crate) -> Cancellable<FileId> {
678 self.with_db(|db| crate_id.data(db).root_file_id)
679 }
680
681 pub fn runnables(&self, file_id: FileId) -> Cancellable<Vec<Runnable>> {
683 self.with_db(|db| runnables::runnables(db, file_id))
684 }
685
686 pub fn related_tests(
688 &self,
689 position: FilePosition,
690 search_scope: Option<SearchScope>,
691 ) -> Cancellable<Vec<Runnable>> {
692 let search_scope = AssertUnwindSafe(search_scope);
693 self.with_db(|db| {
694 let _ = &search_scope;
695 runnables::related_tests(db, position, search_scope.0)
696 })
697 }
698
699 pub fn highlight_related(
701 &self,
702 config: HighlightRelatedConfig,
703 position: FilePosition,
704 ) -> Cancellable<Option<Vec<HighlightedRange>>> {
705 self.with_db(|db| {
706 highlight_related::highlight_related(&Semantics::new(db), config, position)
707 })
708 }
709
710 pub fn highlight(
712 &self,
713 highlight_config: HighlightConfig<'_>,
714 file_id: FileId,
715 ) -> Cancellable<Vec<HlRange>> {
716 self.with_db(|db| syntax_highlighting::highlight(db, &highlight_config, file_id, None))
717 }
718
719 pub fn highlight_range(
721 &self,
722 highlight_config: HighlightConfig<'_>,
723 frange: FileRange,
724 ) -> Cancellable<Vec<HlRange>> {
725 self.with_db(|db| {
726 syntax_highlighting::highlight(
727 db,
728 &highlight_config,
729 frange.file_id,
730 Some(frange.range),
731 )
732 })
733 }
734
735 pub fn highlight_as_html_with_config(
737 &self,
738 config: HighlightConfig<'_>,
739 file_id: FileId,
740 rainbow: bool,
741 ) -> Cancellable<String> {
742 self.with_db(|db| {
743 syntax_highlighting::highlight_as_html_with_config(db, &config, file_id, rainbow)
744 })
745 }
746
747 pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancellable<String> {
749 self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
750 }
751
752 pub fn completions(
754 &self,
755 config: &CompletionConfig<'_>,
756 position: FilePosition,
757 trigger_character: Option<char>,
758 ) -> Cancellable<Option<Vec<CompletionItem>>> {
759 self.with_db(|db| ide_completion::completions(db, config, position, trigger_character))
760 }
761
762 pub fn resolve_completion_edits(
764 &self,
765 config: &CompletionConfig<'_>,
766 position: FilePosition,
767 imports: impl IntoIterator<Item = String> + std::panic::UnwindSafe,
768 ) -> Cancellable<Vec<TextEdit>> {
769 Ok(self
770 .with_db(|db| ide_completion::resolve_completion_edits(db, config, position, imports))?
771 .unwrap_or_default())
772 }
773
774 pub fn syntax_diagnostics(
776 &self,
777 config: &DiagnosticsConfig,
778 file_id: FileId,
779 ) -> Cancellable<Vec<Diagnostic>> {
780 self.with_db(|db| ide_diagnostics::syntax_diagnostics(db, config, file_id))
781 }
782
783 pub fn semantic_diagnostics(
785 &self,
786 config: &DiagnosticsConfig,
787 resolve: AssistResolveStrategy,
788 file_id: FileId,
789 ) -> Cancellable<Vec<Diagnostic>> {
790 self.with_db(|db| ide_diagnostics::semantic_diagnostics(db, config, &resolve, file_id))
791 }
792
793 pub fn full_diagnostics(
795 &self,
796 config: &DiagnosticsConfig,
797 resolve: AssistResolveStrategy,
798 file_id: FileId,
799 ) -> Cancellable<Vec<Diagnostic>> {
800 self.with_db(|db| ide_diagnostics::full_diagnostics(db, config, &resolve, file_id))
801 }
802
803 pub fn assists_with_fixes(
805 &self,
806 assist_config: &AssistConfig,
807 diagnostics_config: &DiagnosticsConfig,
808 resolve: AssistResolveStrategy,
809 frange: FileRange,
810 ) -> Cancellable<Vec<Assist>> {
811 let include_fixes = match &assist_config.allowed {
812 Some(it) => it.contains(&AssistKind::QuickFix),
813 None => true,
814 };
815
816 self.with_db(|db| {
817 let diagnostic_assists = if diagnostics_config.enabled && include_fixes {
818 ide_diagnostics::full_diagnostics(db, diagnostics_config, &resolve, frange.file_id)
819 .into_iter()
820 .flat_map(|it| it.fixes.unwrap_or_default())
821 .filter(|it| it.target.intersect(frange.range).is_some())
822 .collect()
823 } else {
824 Vec::new()
825 };
826 let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
827 let assists = ide_assists::assists(db, assist_config, resolve, frange);
828
829 let mut res = diagnostic_assists;
830 res.extend(ssr_assists);
831 res.extend(assists);
832
833 res
834 })
835 }
836
837 pub fn rename(
840 &self,
841 position: FilePosition,
842 new_name: &str,
843 config: &RenameConfig,
844 ) -> Cancellable<Result<SourceChange, RenameError>> {
845 self.with_db(|db| rename::rename(db, position, new_name, config))
846 }
847
848 pub fn prepare_rename(
849 &self,
850 position: FilePosition,
851 ) -> Cancellable<Result<RangeInfo<()>, RenameError>> {
852 self.with_db(|db| rename::prepare_rename(db, position))
853 }
854
855 pub fn will_rename_file(
856 &self,
857 file_id: FileId,
858 new_name_stem: &str,
859 config: &RenameConfig,
860 ) -> Cancellable<Option<SourceChange>> {
861 self.with_db(|db| rename::will_rename_file(db, file_id, new_name_stem, config))
862 }
863
864 pub fn structural_search_replace(
865 &self,
866 query: &str,
867 parse_only: bool,
868 resolve_context: FilePosition,
869 selections: Vec<FileRange>,
870 ) -> Cancellable<Result<SourceChange, SsrError>> {
871 self.with_db(|db| {
872 let rule: ide_ssr::SsrRule = query.parse()?;
873 let mut match_finder =
874 ide_ssr::MatchFinder::in_context(db, resolve_context, selections)?;
875 match_finder.add_rule(rule)?;
876 let edits = if parse_only { Default::default() } else { match_finder.edits() };
877 Ok(SourceChange::from_iter(edits))
878 })
879 }
880
881 pub fn annotations(
882 &self,
883 config: &AnnotationConfig<'_>,
884 file_id: FileId,
885 ) -> Cancellable<Vec<Annotation>> {
886 self.with_db(|db| annotations::annotations(db, config, file_id))
887 }
888
889 pub fn resolve_annotation(
890 &self,
891 config: &AnnotationConfig<'_>,
892 annotation: Annotation,
893 ) -> Cancellable<Annotation> {
894 self.with_db(|db| annotations::resolve_annotation(db, config, annotation))
895 }
896
897 pub fn move_item(
898 &self,
899 range: FileRange,
900 direction: Direction,
901 ) -> Cancellable<Option<TextEdit>> {
902 self.with_db(|db| move_item::move_item(db, range, direction))
903 }
904
905 pub fn get_recursive_memory_layout(
906 &self,
907 position: FilePosition,
908 ) -> Cancellable<Option<RecursiveMemoryLayout>> {
909 self.with_db(|db| view_memory_layout(db, position))
910 }
911
912 pub fn get_failed_obligations(&self, offset: TextSize, file_id: FileId) -> Cancellable<String> {
913 self.with_db(|db| {
914 let sema = Semantics::new(db);
915 let source_file = sema.parse_guess_edition(file_id);
916
917 let Some(token) = source_file.syntax().token_at_offset(offset).next() else {
918 return String::new();
919 };
920 sema.get_failed_obligations(token).unwrap_or_default()
921 })
922 }
923
924 pub fn editioned_file_id_to_vfs(&self, file_id: hir::EditionedFileId) -> FileId {
925 file_id.file_id(&self.db)
926 }
927
928 fn with_db<F, T>(&self, f: F) -> Cancellable<T>
942 where
943 F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
944 {
945 hir::attach_db_allow_change(&self.db, || Cancelled::catch(|| f(&self.db)))
947 }
948}
949
950#[test]
951fn analysis_is_send() {
952 fn is_send<T: Send>() {}
953 is_send::<Analysis>();
954}