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 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) -> (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 proc_macro_cwd = Arc::new(
272 TryFrom::try_from(&*std::env::current_dir().unwrap().as_path().to_string_lossy())
273 .unwrap(),
274 );
275 let crate_attrs = Vec::new();
276 cfg_options.insert_atom(sym::test);
277 crate_graph.add_crate_root(
278 file_id,
279 Edition::CURRENT,
280 None,
281 None,
282 cfg_options,
283 None,
284 Env::default(),
285 CrateOrigin::Local { repo: None, name: None },
286 crate_attrs,
287 false,
288 proc_macro_cwd,
289 Arc::new(CrateWorkspaceData {
290 target: Err("fixture has no layout".into()),
291 toolchain: None,
292 }),
293 );
294 change.change_file(file_id, Some(text));
295 change.set_crate_graph(crate_graph);
296
297 host.apply_change(change);
298 (host.analysis(), file_id)
299 }
300
301 pub(crate) fn from_ra_fixture(
302 sema: &Semantics<'_, RootDatabase>,
303 literal: ast::String,
304 expanded: &ast::String,
305 config: &RaFixtureConfig<'_>,
306 ) -> Option<(Analysis, RaFixtureAnalysis)> {
307 Self::from_ra_fixture_with_on_cursor(sema, literal, expanded, config, &mut |_| {})
308 }
309
310 pub(crate) fn from_ra_fixture_with_on_cursor(
312 sema: &Semantics<'_, RootDatabase>,
313 literal: ast::String,
314 expanded: &ast::String,
315 config: &RaFixtureConfig<'_>,
316 on_cursor: &mut dyn FnMut(TextRange),
317 ) -> Option<(Analysis, RaFixtureAnalysis)> {
318 let analysis =
319 RaFixtureAnalysis::analyze_ra_fixture(sema, literal, expanded, config, on_cursor)?;
320 Some((Analysis { db: analysis.db.clone() }, analysis))
321 }
322
323 pub fn status(&self, file_id: Option<FileId>) -> Cancellable<String> {
325 self.with_db(|db| status::status(db, file_id))
326 }
327
328 pub fn source_root_id(&self, file_id: FileId) -> Cancellable<SourceRootId> {
329 self.with_db(|db| db.file_source_root(file_id).source_root_id(db))
330 }
331
332 pub fn is_local_source_root(&self, source_root_id: SourceRootId) -> Cancellable<bool> {
333 self.with_db(|db| {
334 let sr = db.source_root(source_root_id).source_root(db);
335 !sr.is_library
336 })
337 }
338
339 pub fn parallel_prime_caches<F>(&self, num_worker_threads: usize, cb: F) -> Cancellable<()>
340 where
341 F: Fn(ParallelPrimeCachesProgress) + Sync + std::panic::UnwindSafe,
342 {
343 self.with_db(move |db| prime_caches::parallel_prime_caches(db, num_worker_threads, &cb))
344 }
345
346 pub fn file_text(&self, file_id: FileId) -> Cancellable<Arc<str>> {
348 self.with_db(|db| SourceDatabase::file_text(db, file_id).text(db).clone())
349 }
350
351 pub fn parse(&self, file_id: FileId) -> Cancellable<SourceFile> {
353 self.with_db(|db| {
355 let editioned_file_id_wrapper = EditionedFileId::current_edition(&self.db, file_id);
356
357 editioned_file_id_wrapper.parse(db).tree()
358 })
359 }
360
361 pub fn is_library_file(&self, file_id: FileId) -> Cancellable<bool> {
363 self.with_db(|db| {
364 let source_root = db.file_source_root(file_id).source_root_id(db);
365 db.source_root(source_root).source_root(db).is_library
366 })
367 }
368
369 pub fn file_line_index(&self, file_id: FileId) -> Cancellable<Arc<LineIndex>> {
372 self.with_db(|db| line_index(db, file_id).clone())
373 }
374
375 pub fn extend_selection(&self, frange: FileRange) -> Cancellable<TextRange> {
377 self.with_db(|db| extend_selection::extend_selection(db, frange))
378 }
379
380 pub fn matching_brace(&self, position: FilePosition) -> Cancellable<Option<TextSize>> {
383 self.with_db(|db| {
384 let file_id = EditionedFileId::current_edition(&self.db, position.file_id);
385 let parse = file_id.parse(db);
386 let file = parse.tree();
387 matching_brace::matching_brace(&file, position.offset)
388 })
389 }
390
391 pub fn view_syntax_tree(&self, file_id: FileId) -> Cancellable<String> {
392 self.with_db(|db| view_syntax_tree::view_syntax_tree(db, file_id))
393 }
394
395 pub fn view_hir(&self, position: FilePosition) -> Cancellable<String> {
396 self.with_db(|db| view_hir::view_hir(db, position))
397 }
398
399 pub fn view_mir(&self, position: FilePosition) -> Cancellable<String> {
400 self.with_db(|db| view_mir::view_mir(db, position))
401 }
402
403 pub fn interpret_function(&self, position: FilePosition) -> Cancellable<String> {
404 self.with_db(|db| interpret::interpret(db, position))
405 }
406
407 pub fn view_item_tree(&self, file_id: FileId) -> Cancellable<String> {
408 self.with_db(|db| view_item_tree::view_item_tree(db, file_id))
409 }
410
411 pub fn discover_test_roots(&self) -> Cancellable<Vec<TestItem>> {
412 self.with_db(test_explorer::discover_test_roots)
413 }
414
415 pub fn discover_tests_in_crate_by_test_id(&self, crate_id: &str) -> Cancellable<Vec<TestItem>> {
416 self.with_db(|db| test_explorer::discover_tests_in_crate_by_test_id(db, crate_id))
417 }
418
419 pub fn discover_tests_in_crate(&self, crate_id: Crate) -> Cancellable<Vec<TestItem>> {
420 self.with_db(|db| test_explorer::discover_tests_in_crate(db, crate_id))
421 }
422
423 pub fn discover_tests_in_file(&self, file_id: FileId) -> Cancellable<Vec<TestItem>> {
424 self.with_db(|db| test_explorer::discover_tests_in_file(db, file_id))
425 }
426
427 pub fn view_crate_graph(&self, full: bool) -> Cancellable<String> {
429 self.with_db(|db| view_crate_graph::view_crate_graph(db, full))
430 }
431
432 pub fn fetch_crates(&self) -> Cancellable<FxIndexSet<CrateInfo>> {
433 self.with_db(fetch_crates::fetch_crates)
434 }
435
436 pub fn expand_macro(&self, position: FilePosition) -> Cancellable<Option<ExpandedMacro>> {
437 self.with_db(|db| expand_macro::expand_macro(db, position))
438 }
439
440 pub fn join_lines(&self, config: &JoinLinesConfig, frange: FileRange) -> Cancellable<TextEdit> {
443 self.with_db(|db| {
444 let editioned_file_id_wrapper =
445 EditionedFileId::current_edition(&self.db, frange.file_id);
446 let parse = editioned_file_id_wrapper.parse(db);
447 join_lines::join_lines(config, &parse.tree(), frange.range)
448 })
449 }
450
451 pub fn on_enter(&self, position: FilePosition) -> Cancellable<Option<TextEdit>> {
455 self.with_db(|db| typing::on_enter(db, position))
456 }
457
458 pub const SUPPORTED_TRIGGER_CHARS: &[char] = typing::TRIGGER_CHARS;
459
460 pub fn on_char_typed(
465 &self,
466 position: FilePosition,
467 char_typed: char,
468 ) -> Cancellable<Option<SourceChange>> {
469 if !typing::TRIGGER_CHARS.contains(&char_typed) {
471 return Ok(None);
472 }
473
474 self.with_db(|db| typing::on_char_typed(db, position, char_typed))
475 }
476
477 pub fn file_structure(
480 &self,
481 config: &FileStructureConfig,
482 file_id: FileId,
483 ) -> Cancellable<Vec<StructureNode>> {
484 self.with_db(|db| {
486 let editioned_file_id_wrapper = EditionedFileId::current_edition(&self.db, file_id);
487 let source_file = editioned_file_id_wrapper.parse(db).tree();
488 file_structure::file_structure(&source_file, config)
489 })
490 }
491
492 pub fn inlay_hints(
494 &self,
495 config: &InlayHintsConfig<'_>,
496 file_id: FileId,
497 range: Option<TextRange>,
498 ) -> Cancellable<Vec<InlayHint>> {
499 self.with_db(|db| inlay_hints::inlay_hints(db, file_id, range, config))
500 }
501 pub fn inlay_hints_resolve(
502 &self,
503 config: &InlayHintsConfig<'_>,
504 file_id: FileId,
505 resolve_range: TextRange,
506 hash: u64,
507 hasher: impl Fn(&InlayHint) -> u64 + Send + UnwindSafe,
508 ) -> Cancellable<Option<InlayHint>> {
509 self.with_db(|db| {
510 inlay_hints::inlay_hints_resolve(db, file_id, resolve_range, hash, config, hasher)
511 })
512 }
513
514 pub fn folding_ranges(&self, file_id: FileId, collapsed_text: bool) -> Cancellable<Vec<Fold>> {
516 self.with_db(|db| {
517 let editioned_file_id_wrapper = EditionedFileId::current_edition(&self.db, file_id);
518
519 folding_ranges::folding_ranges(
520 &editioned_file_id_wrapper.parse(db).tree(),
521 collapsed_text,
522 )
523 })
524 }
525
526 pub fn symbol_search(&self, query: Query, limit: usize) -> Cancellable<Vec<NavigationTarget>> {
528 Cancelled::catch(|| {
531 let symbols = symbol_index::world_symbols(&self.db, query);
532 hir::attach_db(&self.db, || {
533 symbols
534 .into_iter()
535 .filter_map(|s| s.try_to_nav(&Semantics::new(&self.db)))
536 .take(limit)
537 .map(UpmappingResult::call_site)
538 .collect::<Vec<_>>()
539 })
540 })
541 }
542
543 pub fn goto_definition(
545 &self,
546 position: FilePosition,
547 config: &GotoDefinitionConfig<'_>,
548 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
549 self.with_db(|db| goto_definition::goto_definition(db, position, config))
550 }
551
552 pub fn goto_declaration(
554 &self,
555 position: FilePosition,
556 config: &GotoDefinitionConfig<'_>,
557 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
558 self.with_db(|db| goto_declaration::goto_declaration(db, position, config))
559 }
560
561 pub fn goto_implementation(
563 &self,
564 config: &GotoImplementationConfig,
565 position: FilePosition,
566 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
567 self.with_db(|db| goto_implementation::goto_implementation(db, config, position))
568 }
569
570 pub fn goto_type_definition(
572 &self,
573 position: FilePosition,
574 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
575 self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
576 }
577
578 pub fn find_all_refs(
579 &self,
580 position: FilePosition,
581 config: &FindAllRefsConfig<'_>,
582 ) -> Cancellable<Option<Vec<ReferenceSearchResult>>> {
583 let config = AssertUnwindSafe(config);
584 self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, &config))
585 }
586
587 pub fn hover(
589 &self,
590 config: &HoverConfig<'_>,
591 range: FileRange,
592 ) -> Cancellable<Option<RangeInfo<HoverResult>>> {
593 self.with_db(|db| hover::hover(db, range, config))
594 }
595
596 pub fn moniker(
598 &self,
599 position: FilePosition,
600 ) -> Cancellable<Option<RangeInfo<Vec<moniker::MonikerResult>>>> {
601 self.with_db(|db| moniker::moniker(db, position))
602 }
603
604 pub fn external_docs(
609 &self,
610 position: FilePosition,
611 target_dir: Option<&str>,
612 sysroot: Option<&str>,
613 ) -> Cancellable<doc_links::DocumentationLinks> {
614 self.with_db(|db| {
615 doc_links::external_docs(db, position, target_dir, sysroot).unwrap_or_default()
616 })
617 }
618
619 pub fn signature_help(&self, position: FilePosition) -> Cancellable<Option<SignatureHelp>> {
621 self.with_db(|db| signature_help::signature_help(db, position))
622 }
623
624 pub fn call_hierarchy(
626 &self,
627 position: FilePosition,
628 config: &CallHierarchyConfig<'_>,
629 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
630 self.with_db(|db| call_hierarchy::call_hierarchy(db, position, config))
631 }
632
633 pub fn incoming_calls(
635 &self,
636 config: &CallHierarchyConfig<'_>,
637 position: FilePosition,
638 ) -> Cancellable<Option<Vec<CallItem>>> {
639 self.with_db(|db| call_hierarchy::incoming_calls(db, config, position))
640 }
641
642 pub fn outgoing_calls(
644 &self,
645 config: &CallHierarchyConfig<'_>,
646 position: FilePosition,
647 ) -> Cancellable<Option<Vec<CallItem>>> {
648 self.with_db(|db| call_hierarchy::outgoing_calls(db, config, position))
649 }
650
651 pub fn parent_module(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
653 self.with_db(|db| parent_module::parent_module(db, position))
654 }
655
656 pub fn child_modules(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
658 self.with_db(|db| child_modules::child_modules(db, position))
659 }
660
661 pub fn crates_for(&self, file_id: FileId) -> Cancellable<Vec<Crate>> {
663 self.with_db(|db| parent_module::crates_for(db, file_id))
664 }
665
666 pub fn transitive_rev_deps(&self, crate_id: Crate) -> Cancellable<Vec<Crate>> {
668 self.with_db(|db| Vec::from_iter(crate_id.transitive_rev_deps(db)))
669 }
670
671 pub fn relevant_crates_for(&self, file_id: FileId) -> Cancellable<Vec<Crate>> {
673 self.with_db(|db| relevant_crates(db, file_id).to_vec())
674 }
675
676 pub fn crate_edition(&self, crate_id: Crate) -> Cancellable<Edition> {
678 self.with_db(|db| crate_id.data(db).edition)
679 }
680
681 pub fn is_proc_macro_crate(&self, crate_id: Crate) -> Cancellable<bool> {
683 self.with_db(|db| crate_id.data(db).is_proc_macro)
684 }
685
686 pub fn is_crate_no_std(&self, crate_id: Crate) -> Cancellable<bool> {
688 self.with_db(|db| crate_def_map(db, crate_id).is_no_std())
689 }
690
691 pub fn crate_root(&self, crate_id: Crate) -> Cancellable<FileId> {
693 self.with_db(|db| crate_id.data(db).root_file_id)
694 }
695
696 pub fn runnables(&self, file_id: FileId) -> Cancellable<Vec<Runnable>> {
698 self.with_db(|db| runnables::runnables(db, file_id))
699 }
700
701 pub fn related_tests(
703 &self,
704 position: FilePosition,
705 search_scope: Option<SearchScope>,
706 ) -> Cancellable<Vec<Runnable>> {
707 let search_scope = AssertUnwindSafe(search_scope);
708 self.with_db(|db| {
709 let _ = &search_scope;
710 runnables::related_tests(db, position, search_scope.0)
711 })
712 }
713
714 pub fn highlight_related(
716 &self,
717 config: HighlightRelatedConfig,
718 position: FilePosition,
719 ) -> Cancellable<Option<Vec<HighlightedRange>>> {
720 self.with_db(|db| {
721 highlight_related::highlight_related(&Semantics::new(db), config, position)
722 })
723 }
724
725 pub fn highlight(
727 &self,
728 highlight_config: HighlightConfig<'_>,
729 file_id: FileId,
730 ) -> Cancellable<Vec<HlRange>> {
731 self.with_db(|db| syntax_highlighting::highlight(db, &highlight_config, file_id, None))
732 }
733
734 pub fn highlight_range(
736 &self,
737 highlight_config: HighlightConfig<'_>,
738 frange: FileRange,
739 ) -> Cancellable<Vec<HlRange>> {
740 self.with_db(|db| {
741 syntax_highlighting::highlight(
742 db,
743 &highlight_config,
744 frange.file_id,
745 Some(frange.range),
746 )
747 })
748 }
749
750 pub fn highlight_as_html_with_config(
752 &self,
753 config: HighlightConfig<'_>,
754 file_id: FileId,
755 rainbow: bool,
756 ) -> Cancellable<String> {
757 self.with_db(|db| {
758 syntax_highlighting::highlight_as_html_with_config(db, &config, file_id, rainbow)
759 })
760 }
761
762 pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancellable<String> {
764 self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
765 }
766
767 pub fn completions(
769 &self,
770 config: &CompletionConfig<'_>,
771 position: FilePosition,
772 trigger_character: Option<char>,
773 ) -> Cancellable<Option<Vec<CompletionItem>>> {
774 self.with_db(|db| ide_completion::completions(db, config, position, trigger_character))
775 }
776
777 pub fn resolve_completion_edits(
779 &self,
780 config: &CompletionConfig<'_>,
781 position: FilePosition,
782 imports: impl IntoIterator<Item = CompletionItemImport> + std::panic::UnwindSafe,
783 ) -> Cancellable<Vec<TextEdit>> {
784 Ok(self
785 .with_db(|db| ide_completion::resolve_completion_edits(db, config, position, imports))?
786 .unwrap_or_default())
787 }
788
789 pub fn syntax_diagnostics(
791 &self,
792 config: &DiagnosticsConfig,
793 file_id: FileId,
794 ) -> Cancellable<Vec<Diagnostic>> {
795 self.with_db(|db| ide_diagnostics::syntax_diagnostics(db, config, file_id))
796 }
797
798 pub fn semantic_diagnostics(
800 &self,
801 config: &DiagnosticsConfig,
802 resolve: AssistResolveStrategy,
803 file_id: FileId,
804 ) -> Cancellable<Vec<Diagnostic>> {
805 self.with_db(|db| ide_diagnostics::semantic_diagnostics(db, config, &resolve, file_id))
806 }
807
808 pub fn full_diagnostics(
810 &self,
811 config: &DiagnosticsConfig,
812 resolve: AssistResolveStrategy,
813 file_id: FileId,
814 ) -> Cancellable<Vec<Diagnostic>> {
815 self.with_db(|db| ide_diagnostics::full_diagnostics(db, config, &resolve, file_id))
816 }
817
818 pub fn assists_with_fixes(
820 &self,
821 assist_config: &AssistConfig,
822 diagnostics_config: &DiagnosticsConfig,
823 resolve: AssistResolveStrategy,
824 frange: FileRange,
825 ) -> Cancellable<Vec<Assist>> {
826 let include_fixes = match &assist_config.allowed {
827 Some(it) => it.contains(&AssistKind::QuickFix),
828 None => true,
829 };
830
831 self.with_db(|db| {
832 let diagnostic_assists = if diagnostics_config.enabled && include_fixes {
833 ide_diagnostics::full_diagnostics(db, diagnostics_config, &resolve, frange.file_id)
834 .into_iter()
835 .flat_map(|it| it.fixes.unwrap_or_default())
836 .filter(|it| it.target.intersect(frange.range).is_some())
837 .collect()
838 } else {
839 Vec::new()
840 };
841 let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
842 let assists = ide_assists::assists(db, assist_config, resolve, frange);
843
844 let mut res = diagnostic_assists;
845 res.extend(ssr_assists);
846 res.extend(assists);
847
848 res
849 })
850 }
851
852 pub fn rename(
855 &self,
856 position: FilePosition,
857 new_name: &str,
858 config: &RenameConfig,
859 ) -> Cancellable<Result<SourceChange, RenameError>> {
860 self.with_db(|db| rename::rename(db, position, new_name, config))
861 }
862
863 pub fn prepare_rename(
864 &self,
865 position: FilePosition,
866 ) -> Cancellable<Result<RangeInfo<()>, RenameError>> {
867 self.with_db(|db| rename::prepare_rename(db, position))
868 }
869
870 pub fn will_rename_file(
871 &self,
872 file_id: FileId,
873 new_name_stem: &str,
874 config: &RenameConfig,
875 ) -> Cancellable<Option<SourceChange>> {
876 self.with_db(|db| rename::will_rename_file(db, file_id, new_name_stem, config))
877 }
878
879 pub fn structural_search_replace(
880 &self,
881 query: &str,
882 parse_only: bool,
883 resolve_context: FilePosition,
884 selections: Vec<FileRange>,
885 ) -> Cancellable<Result<SourceChange, SsrError>> {
886 self.with_db(|db| {
887 let rule: ide_ssr::SsrRule = query.parse()?;
888 let mut match_finder =
889 ide_ssr::MatchFinder::in_context(db, resolve_context, selections)?;
890 match_finder.add_rule(rule)?;
891 let edits = if parse_only { Default::default() } else { match_finder.edits() };
892 Ok(SourceChange::from_iter(edits))
893 })
894 }
895
896 pub fn annotations(
897 &self,
898 config: &AnnotationConfig<'_>,
899 file_id: FileId,
900 ) -> Cancellable<Vec<Annotation>> {
901 self.with_db(|db| annotations::annotations(db, config, file_id))
902 }
903
904 pub fn resolve_annotation(
905 &self,
906 config: &AnnotationConfig<'_>,
907 annotation: Annotation,
908 ) -> Cancellable<Annotation> {
909 self.with_db(|db| annotations::resolve_annotation(db, config, annotation))
910 }
911
912 pub fn move_item(
913 &self,
914 range: FileRange,
915 direction: Direction,
916 ) -> Cancellable<Option<TextEdit>> {
917 self.with_db(|db| move_item::move_item(db, range, direction))
918 }
919
920 pub fn get_recursive_memory_layout(
921 &self,
922 position: FilePosition,
923 ) -> Cancellable<Option<RecursiveMemoryLayout>> {
924 self.with_db(|db| view_memory_layout(db, position))
925 }
926
927 pub fn get_failed_obligations(&self, offset: TextSize, file_id: FileId) -> Cancellable<String> {
928 self.with_db(|db| {
929 let sema = Semantics::new(db);
930 let source_file = sema.parse_guess_edition(file_id);
931
932 let Some(token) = source_file.syntax().token_at_offset(offset).next() else {
933 return String::new();
934 };
935 sema.get_failed_obligations(token).unwrap_or_default()
936 })
937 }
938
939 pub fn editioned_file_id_to_vfs(&self, file_id: hir::EditionedFileId) -> FileId {
940 file_id.file_id(&self.db)
941 }
942
943 fn with_db<F, T>(&self, f: F) -> Cancellable<T>
957 where
958 F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
959 {
960 hir::attach_db_allow_change(&self.db, || Cancelled::catch(|| f(&self.db)))
962 }
963}
964
965#[test]
966fn analysis_is_send() {
967 fn is_send<T: Send>() {}
968 is_send::<Analysis>();
969}