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