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::{
67 FxHashMap, FxIndexSet, LineIndexDatabase,
68 base_db::{
69 CrateOrigin, CrateWorkspaceData, Env, FileSet, RootQueryDb, SourceDatabase, VfsPath,
70 salsa::{Cancelled, Database},
71 },
72 prime_caches, symbol_index,
73};
74use ide_db::{MiniCore, ra_fixture::RaFixtureAnalysis};
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 search::{ReferenceCategory, SearchScope},
139 source_change::{FileSystemEdit, SnippetEdit, SourceChange},
140 symbol_index::Query,
141 text_edit::{Indel, TextEdit},
142};
143pub use ide_diagnostics::{Diagnostic, DiagnosticCode, DiagnosticsConfig};
144pub use ide_ssr::SsrError;
145pub use span::Edition;
146pub use syntax::{TextRange, TextSize};
147
148pub type Cancellable<T> = Result<T, Cancelled>;
149
150#[derive(Debug, UpmapFromRaFixture)]
152pub struct RangeInfo<T> {
153 pub range: TextRange,
154 pub info: T,
155}
156
157impl<T> RangeInfo<T> {
158 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
159 RangeInfo { range, info }
160 }
161}
162
163#[derive(Debug)]
165pub struct AnalysisHost {
166 db: RootDatabase,
167}
168
169impl AnalysisHost {
170 pub fn new(lru_capacity: Option<u16>) -> AnalysisHost {
171 AnalysisHost { db: RootDatabase::new(lru_capacity) }
172 }
173
174 pub fn with_database(db: RootDatabase) -> AnalysisHost {
175 AnalysisHost { db }
176 }
177
178 pub fn update_lru_capacity(&mut self, lru_capacity: Option<u16>) {
179 self.db.update_base_query_lru_capacities(lru_capacity);
180 }
181
182 pub fn update_lru_capacities(&mut self, lru_capacities: &FxHashMap<Box<str>, u16>) {
183 self.db.update_lru_capacities(lru_capacities);
184 }
185
186 pub fn analysis(&self) -> Analysis {
189 Analysis { db: self.db.clone() }
190 }
191
192 pub fn apply_change(&mut self, change: ChangeWithProcMacros) {
195 self.db.apply_change(change);
196 }
197
198 pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes, usize)> {
200 self.db.per_query_memory_usage()
201 }
202 pub fn trigger_cancellation(&mut self) {
203 self.db.trigger_cancellation();
204 }
205 pub fn trigger_garbage_collection(&mut self) {
206 self.db.trigger_lru_eviction();
207 unsafe { hir::collect_ty_garbage() };
209 }
210 pub fn raw_database(&self) -> &RootDatabase {
211 &self.db
212 }
213 pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
214 &mut self.db
215 }
216}
217
218impl Default for AnalysisHost {
219 fn default() -> AnalysisHost {
220 AnalysisHost::new(None)
221 }
222}
223
224#[derive(Debug)]
229pub struct Analysis {
230 db: RootDatabase,
231}
232
233impl Analysis {
240 pub fn from_single_file(text: String) -> (Analysis, FileId) {
244 let mut host = AnalysisHost::default();
245 let file_id = FileId::from_raw(0);
246 let mut file_set = FileSet::default();
247 file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_owned()));
248 let source_root = SourceRoot::new_local(file_set);
249
250 let mut change = ChangeWithProcMacros::default();
251 change.set_roots(vec![source_root]);
252 let mut crate_graph = CrateGraphBuilder::default();
253 let mut cfg_options = CfgOptions::default();
256
257 let proc_macro_cwd = Arc::new(
259 TryFrom::try_from(&*std::env::current_dir().unwrap().as_path().to_string_lossy())
260 .unwrap(),
261 );
262 let crate_attrs = Vec::new();
263 cfg_options.insert_atom(sym::test);
264 crate_graph.add_crate_root(
265 file_id,
266 Edition::CURRENT,
267 None,
268 None,
269 cfg_options,
270 None,
271 Env::default(),
272 CrateOrigin::Local { repo: None, name: None },
273 crate_attrs,
274 false,
275 proc_macro_cwd,
276 Arc::new(CrateWorkspaceData {
277 target: Err("fixture has no layout".into()),
278 toolchain: None,
279 }),
280 );
281 change.change_file(file_id, Some(text));
282 change.set_crate_graph(crate_graph);
283
284 host.apply_change(change);
285 (host.analysis(), file_id)
286 }
287
288 pub(crate) fn from_ra_fixture(
289 sema: &Semantics<'_, RootDatabase>,
290 literal: ast::String,
291 expanded: &ast::String,
292 minicore: MiniCore<'_>,
293 ) -> Option<(Analysis, RaFixtureAnalysis)> {
294 Self::from_ra_fixture_with_on_cursor(sema, literal, expanded, minicore, &mut |_| {})
295 }
296
297 pub(crate) fn from_ra_fixture_with_on_cursor(
299 sema: &Semantics<'_, RootDatabase>,
300 literal: ast::String,
301 expanded: &ast::String,
302 minicore: MiniCore<'_>,
303 on_cursor: &mut dyn FnMut(TextRange),
304 ) -> Option<(Analysis, RaFixtureAnalysis)> {
305 let analysis =
306 RaFixtureAnalysis::analyze_ra_fixture(sema, literal, expanded, minicore, on_cursor)?;
307 Some((Analysis { db: analysis.db.clone() }, analysis))
308 }
309
310 pub fn status(&self, file_id: Option<FileId>) -> Cancellable<String> {
312 self.with_db(|db| status::status(db, file_id))
313 }
314
315 pub fn source_root_id(&self, file_id: FileId) -> Cancellable<SourceRootId> {
316 self.with_db(|db| db.file_source_root(file_id).source_root_id(db))
317 }
318
319 pub fn is_local_source_root(&self, source_root_id: SourceRootId) -> Cancellable<bool> {
320 self.with_db(|db| {
321 let sr = db.source_root(source_root_id).source_root(db);
322 !sr.is_library
323 })
324 }
325
326 pub fn parallel_prime_caches<F>(&self, num_worker_threads: usize, cb: F) -> Cancellable<()>
327 where
328 F: Fn(ParallelPrimeCachesProgress) + Sync + std::panic::UnwindSafe,
329 {
330 self.with_db(move |db| prime_caches::parallel_prime_caches(db, num_worker_threads, &cb))
331 }
332
333 pub fn file_text(&self, file_id: FileId) -> Cancellable<Arc<str>> {
335 self.with_db(|db| SourceDatabase::file_text(db, file_id).text(db).clone())
336 }
337
338 pub fn parse(&self, file_id: FileId) -> Cancellable<SourceFile> {
340 self.with_db(|db| {
342 let editioned_file_id_wrapper = EditionedFileId::current_edition(&self.db, file_id);
343
344 db.parse(editioned_file_id_wrapper).tree()
345 })
346 }
347
348 pub fn is_library_file(&self, file_id: FileId) -> Cancellable<bool> {
350 self.with_db(|db| {
351 let source_root = db.file_source_root(file_id).source_root_id(db);
352 db.source_root(source_root).source_root(db).is_library
353 })
354 }
355
356 pub fn file_line_index(&self, file_id: FileId) -> Cancellable<Arc<LineIndex>> {
359 self.with_db(|db| db.line_index(file_id))
360 }
361
362 pub fn extend_selection(&self, frange: FileRange) -> Cancellable<TextRange> {
364 self.with_db(|db| extend_selection::extend_selection(db, frange))
365 }
366
367 pub fn matching_brace(&self, position: FilePosition) -> Cancellable<Option<TextSize>> {
370 self.with_db(|db| {
371 let file_id = EditionedFileId::current_edition(&self.db, position.file_id);
372 let parse = db.parse(file_id);
373 let file = parse.tree();
374 matching_brace::matching_brace(&file, position.offset)
375 })
376 }
377
378 pub fn view_syntax_tree(&self, file_id: FileId) -> Cancellable<String> {
379 self.with_db(|db| view_syntax_tree::view_syntax_tree(db, file_id))
380 }
381
382 pub fn view_hir(&self, position: FilePosition) -> Cancellable<String> {
383 self.with_db(|db| view_hir::view_hir(db, position))
384 }
385
386 pub fn view_mir(&self, position: FilePosition) -> Cancellable<String> {
387 self.with_db(|db| view_mir::view_mir(db, position))
388 }
389
390 pub fn interpret_function(&self, position: FilePosition) -> Cancellable<String> {
391 self.with_db(|db| interpret::interpret(db, position))
392 }
393
394 pub fn view_item_tree(&self, file_id: FileId) -> Cancellable<String> {
395 self.with_db(|db| view_item_tree::view_item_tree(db, file_id))
396 }
397
398 pub fn discover_test_roots(&self) -> Cancellable<Vec<TestItem>> {
399 self.with_db(test_explorer::discover_test_roots)
400 }
401
402 pub fn discover_tests_in_crate_by_test_id(&self, crate_id: &str) -> Cancellable<Vec<TestItem>> {
403 self.with_db(|db| test_explorer::discover_tests_in_crate_by_test_id(db, crate_id))
404 }
405
406 pub fn discover_tests_in_crate(&self, crate_id: Crate) -> Cancellable<Vec<TestItem>> {
407 self.with_db(|db| test_explorer::discover_tests_in_crate(db, crate_id))
408 }
409
410 pub fn discover_tests_in_file(&self, file_id: FileId) -> Cancellable<Vec<TestItem>> {
411 self.with_db(|db| test_explorer::discover_tests_in_file(db, file_id))
412 }
413
414 pub fn view_crate_graph(&self, full: bool) -> Cancellable<Result<String, String>> {
416 self.with_db(|db| view_crate_graph::view_crate_graph(db, full))
417 }
418
419 pub fn fetch_crates(&self) -> Cancellable<FxIndexSet<CrateInfo>> {
420 self.with_db(fetch_crates::fetch_crates)
421 }
422
423 pub fn expand_macro(&self, position: FilePosition) -> Cancellable<Option<ExpandedMacro>> {
424 self.with_db(|db| expand_macro::expand_macro(db, position))
425 }
426
427 pub fn join_lines(&self, config: &JoinLinesConfig, frange: FileRange) -> Cancellable<TextEdit> {
430 self.with_db(|db| {
431 let editioned_file_id_wrapper =
432 EditionedFileId::current_edition(&self.db, frange.file_id);
433 let parse = db.parse(editioned_file_id_wrapper);
434 join_lines::join_lines(config, &parse.tree(), frange.range)
435 })
436 }
437
438 pub fn on_enter(&self, position: FilePosition) -> Cancellable<Option<TextEdit>> {
442 self.with_db(|db| typing::on_enter(db, position))
443 }
444
445 pub const SUPPORTED_TRIGGER_CHARS: &[char] = typing::TRIGGER_CHARS;
446
447 pub fn on_char_typed(
452 &self,
453 position: FilePosition,
454 char_typed: char,
455 ) -> Cancellable<Option<SourceChange>> {
456 if !typing::TRIGGER_CHARS.contains(&char_typed) {
458 return Ok(None);
459 }
460
461 self.with_db(|db| typing::on_char_typed(db, position, char_typed))
462 }
463
464 pub fn file_structure(
467 &self,
468 config: &FileStructureConfig,
469 file_id: FileId,
470 ) -> Cancellable<Vec<StructureNode>> {
471 self.with_db(|db| {
473 let editioned_file_id_wrapper = EditionedFileId::current_edition(&self.db, file_id);
474 let source_file = db.parse(editioned_file_id_wrapper).tree();
475 file_structure::file_structure(&source_file, config)
476 })
477 }
478
479 pub fn inlay_hints(
481 &self,
482 config: &InlayHintsConfig<'_>,
483 file_id: FileId,
484 range: Option<TextRange>,
485 ) -> Cancellable<Vec<InlayHint>> {
486 self.with_db(|db| inlay_hints::inlay_hints(db, file_id, range, config))
487 }
488 pub fn inlay_hints_resolve(
489 &self,
490 config: &InlayHintsConfig<'_>,
491 file_id: FileId,
492 resolve_range: TextRange,
493 hash: u64,
494 hasher: impl Fn(&InlayHint) -> u64 + Send + UnwindSafe,
495 ) -> Cancellable<Option<InlayHint>> {
496 self.with_db(|db| {
497 inlay_hints::inlay_hints_resolve(db, file_id, resolve_range, hash, config, hasher)
498 })
499 }
500
501 pub fn folding_ranges(&self, file_id: FileId) -> Cancellable<Vec<Fold>> {
503 self.with_db(|db| {
504 let editioned_file_id_wrapper = EditionedFileId::current_edition(&self.db, file_id);
505
506 folding_ranges::folding_ranges(&db.parse(editioned_file_id_wrapper).tree())
507 })
508 }
509
510 pub fn symbol_search(&self, query: Query, limit: usize) -> Cancellable<Vec<NavigationTarget>> {
512 Cancelled::catch(|| {
515 let symbols = symbol_index::world_symbols(&self.db, query);
516 hir::attach_db(&self.db, || {
517 symbols
518 .into_iter()
519 .filter_map(|s| s.try_to_nav(&Semantics::new(&self.db)))
520 .take(limit)
521 .map(UpmappingResult::call_site)
522 .collect::<Vec<_>>()
523 })
524 })
525 }
526
527 pub fn goto_definition(
529 &self,
530 position: FilePosition,
531 config: &GotoDefinitionConfig<'_>,
532 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
533 self.with_db(|db| goto_definition::goto_definition(db, position, config))
534 }
535
536 pub fn goto_declaration(
538 &self,
539 position: FilePosition,
540 config: &GotoDefinitionConfig<'_>,
541 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
542 self.with_db(|db| goto_declaration::goto_declaration(db, position, config))
543 }
544
545 pub fn goto_implementation(
547 &self,
548 config: &GotoImplementationConfig,
549 position: FilePosition,
550 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
551 self.with_db(|db| goto_implementation::goto_implementation(db, config, position))
552 }
553
554 pub fn goto_type_definition(
556 &self,
557 position: FilePosition,
558 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
559 self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
560 }
561
562 pub fn find_all_refs(
563 &self,
564 position: FilePosition,
565 config: &FindAllRefsConfig<'_>,
566 ) -> Cancellable<Option<Vec<ReferenceSearchResult>>> {
567 let config = AssertUnwindSafe(config);
568 self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, &config))
569 }
570
571 pub fn hover(
573 &self,
574 config: &HoverConfig<'_>,
575 range: FileRange,
576 ) -> Cancellable<Option<RangeInfo<HoverResult>>> {
577 self.with_db(|db| hover::hover(db, range, config))
578 }
579
580 pub fn moniker(
582 &self,
583 position: FilePosition,
584 ) -> Cancellable<Option<RangeInfo<Vec<moniker::MonikerResult>>>> {
585 self.with_db(|db| moniker::moniker(db, position))
586 }
587
588 pub fn external_docs(
593 &self,
594 position: FilePosition,
595 target_dir: Option<&str>,
596 sysroot: Option<&str>,
597 ) -> Cancellable<doc_links::DocumentationLinks> {
598 self.with_db(|db| {
599 doc_links::external_docs(db, position, target_dir, sysroot).unwrap_or_default()
600 })
601 }
602
603 pub fn signature_help(&self, position: FilePosition) -> Cancellable<Option<SignatureHelp>> {
605 self.with_db(|db| signature_help::signature_help(db, position))
606 }
607
608 pub fn call_hierarchy(
610 &self,
611 position: FilePosition,
612 config: &CallHierarchyConfig<'_>,
613 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
614 self.with_db(|db| call_hierarchy::call_hierarchy(db, position, config))
615 }
616
617 pub fn incoming_calls(
619 &self,
620 config: &CallHierarchyConfig<'_>,
621 position: FilePosition,
622 ) -> Cancellable<Option<Vec<CallItem>>> {
623 self.with_db(|db| call_hierarchy::incoming_calls(db, config, position))
624 }
625
626 pub fn outgoing_calls(
628 &self,
629 config: &CallHierarchyConfig<'_>,
630 position: FilePosition,
631 ) -> Cancellable<Option<Vec<CallItem>>> {
632 self.with_db(|db| call_hierarchy::outgoing_calls(db, config, position))
633 }
634
635 pub fn parent_module(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
637 self.with_db(|db| parent_module::parent_module(db, position))
638 }
639
640 pub fn child_modules(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
642 self.with_db(|db| child_modules::child_modules(db, position))
643 }
644
645 pub fn crates_for(&self, file_id: FileId) -> Cancellable<Vec<Crate>> {
647 self.with_db(|db| parent_module::crates_for(db, file_id))
648 }
649
650 pub fn transitive_rev_deps(&self, crate_id: Crate) -> Cancellable<Vec<Crate>> {
652 self.with_db(|db| Vec::from_iter(crate_id.transitive_rev_deps(db)))
653 }
654
655 pub fn relevant_crates_for(&self, file_id: FileId) -> Cancellable<Vec<Crate>> {
657 self.with_db(|db| db.relevant_crates(file_id).iter().copied().collect())
658 }
659
660 pub fn crate_edition(&self, crate_id: Crate) -> Cancellable<Edition> {
662 self.with_db(|db| crate_id.data(db).edition)
663 }
664
665 pub fn is_proc_macro_crate(&self, crate_id: Crate) -> Cancellable<bool> {
667 self.with_db(|db| crate_id.data(db).is_proc_macro)
668 }
669
670 pub fn is_crate_no_std(&self, crate_id: Crate) -> Cancellable<bool> {
672 self.with_db(|db| crate_def_map(db, crate_id).is_no_std())
673 }
674
675 pub fn crate_root(&self, crate_id: Crate) -> Cancellable<FileId> {
677 self.with_db(|db| crate_id.data(db).root_file_id)
678 }
679
680 pub fn runnables(&self, file_id: FileId) -> Cancellable<Vec<Runnable>> {
682 self.with_db(|db| runnables::runnables(db, file_id))
683 }
684
685 pub fn related_tests(
687 &self,
688 position: FilePosition,
689 search_scope: Option<SearchScope>,
690 ) -> Cancellable<Vec<Runnable>> {
691 let search_scope = AssertUnwindSafe(search_scope);
692 self.with_db(|db| {
693 let _ = &search_scope;
694 runnables::related_tests(db, position, search_scope.0)
695 })
696 }
697
698 pub fn highlight_related(
700 &self,
701 config: HighlightRelatedConfig,
702 position: FilePosition,
703 ) -> Cancellable<Option<Vec<HighlightedRange>>> {
704 self.with_db(|db| {
705 highlight_related::highlight_related(&Semantics::new(db), config, position)
706 })
707 }
708
709 pub fn highlight(
711 &self,
712 highlight_config: HighlightConfig<'_>,
713 file_id: FileId,
714 ) -> Cancellable<Vec<HlRange>> {
715 self.with_db(|db| syntax_highlighting::highlight(db, &highlight_config, file_id, None))
716 }
717
718 pub fn highlight_range(
720 &self,
721 highlight_config: HighlightConfig<'_>,
722 frange: FileRange,
723 ) -> Cancellable<Vec<HlRange>> {
724 self.with_db(|db| {
725 syntax_highlighting::highlight(
726 db,
727 &highlight_config,
728 frange.file_id,
729 Some(frange.range),
730 )
731 })
732 }
733
734 pub fn highlight_as_html_with_config(
736 &self,
737 config: HighlightConfig<'_>,
738 file_id: FileId,
739 rainbow: bool,
740 ) -> Cancellable<String> {
741 self.with_db(|db| {
742 syntax_highlighting::highlight_as_html_with_config(db, &config, file_id, rainbow)
743 })
744 }
745
746 pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancellable<String> {
748 self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
749 }
750
751 pub fn completions(
753 &self,
754 config: &CompletionConfig<'_>,
755 position: FilePosition,
756 trigger_character: Option<char>,
757 ) -> Cancellable<Option<Vec<CompletionItem>>> {
758 self.with_db(|db| ide_completion::completions(db, config, position, trigger_character))
759 }
760
761 pub fn resolve_completion_edits(
763 &self,
764 config: &CompletionConfig<'_>,
765 position: FilePosition,
766 imports: impl IntoIterator<Item = String> + std::panic::UnwindSafe,
767 ) -> Cancellable<Vec<TextEdit>> {
768 Ok(self
769 .with_db(|db| ide_completion::resolve_completion_edits(db, config, position, imports))?
770 .unwrap_or_default())
771 }
772
773 pub fn syntax_diagnostics(
775 &self,
776 config: &DiagnosticsConfig,
777 file_id: FileId,
778 ) -> Cancellable<Vec<Diagnostic>> {
779 self.with_db(|db| ide_diagnostics::syntax_diagnostics(db, config, file_id))
780 }
781
782 pub fn semantic_diagnostics(
784 &self,
785 config: &DiagnosticsConfig,
786 resolve: AssistResolveStrategy,
787 file_id: FileId,
788 ) -> Cancellable<Vec<Diagnostic>> {
789 self.with_db(|db| ide_diagnostics::semantic_diagnostics(db, config, &resolve, file_id))
790 }
791
792 pub fn full_diagnostics(
794 &self,
795 config: &DiagnosticsConfig,
796 resolve: AssistResolveStrategy,
797 file_id: FileId,
798 ) -> Cancellable<Vec<Diagnostic>> {
799 self.with_db(|db| ide_diagnostics::full_diagnostics(db, config, &resolve, file_id))
800 }
801
802 pub fn assists_with_fixes(
804 &self,
805 assist_config: &AssistConfig,
806 diagnostics_config: &DiagnosticsConfig,
807 resolve: AssistResolveStrategy,
808 frange: FileRange,
809 ) -> Cancellable<Vec<Assist>> {
810 let include_fixes = match &assist_config.allowed {
811 Some(it) => it.contains(&AssistKind::QuickFix),
812 None => true,
813 };
814
815 self.with_db(|db| {
816 let diagnostic_assists = if diagnostics_config.enabled && include_fixes {
817 ide_diagnostics::full_diagnostics(db, diagnostics_config, &resolve, frange.file_id)
818 .into_iter()
819 .flat_map(|it| it.fixes.unwrap_or_default())
820 .filter(|it| it.target.intersect(frange.range).is_some())
821 .collect()
822 } else {
823 Vec::new()
824 };
825 let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
826 let assists = ide_assists::assists(db, assist_config, resolve, frange);
827
828 let mut res = diagnostic_assists;
829 res.extend(ssr_assists);
830 res.extend(assists);
831
832 res
833 })
834 }
835
836 pub fn rename(
839 &self,
840 position: FilePosition,
841 new_name: &str,
842 config: &RenameConfig,
843 ) -> Cancellable<Result<SourceChange, RenameError>> {
844 self.with_db(|db| rename::rename(db, position, new_name, config))
845 }
846
847 pub fn prepare_rename(
848 &self,
849 position: FilePosition,
850 ) -> Cancellable<Result<RangeInfo<()>, RenameError>> {
851 self.with_db(|db| rename::prepare_rename(db, position))
852 }
853
854 pub fn will_rename_file(
855 &self,
856 file_id: FileId,
857 new_name_stem: &str,
858 config: &RenameConfig,
859 ) -> Cancellable<Option<SourceChange>> {
860 self.with_db(|db| rename::will_rename_file(db, file_id, new_name_stem, config))
861 }
862
863 pub fn structural_search_replace(
864 &self,
865 query: &str,
866 parse_only: bool,
867 resolve_context: FilePosition,
868 selections: Vec<FileRange>,
869 ) -> Cancellable<Result<SourceChange, SsrError>> {
870 self.with_db(|db| {
871 let rule: ide_ssr::SsrRule = query.parse()?;
872 let mut match_finder =
873 ide_ssr::MatchFinder::in_context(db, resolve_context, selections)?;
874 match_finder.add_rule(rule)?;
875 let edits = if parse_only { Default::default() } else { match_finder.edits() };
876 Ok(SourceChange::from_iter(edits))
877 })
878 }
879
880 pub fn annotations(
881 &self,
882 config: &AnnotationConfig<'_>,
883 file_id: FileId,
884 ) -> Cancellable<Vec<Annotation>> {
885 self.with_db(|db| annotations::annotations(db, config, file_id))
886 }
887
888 pub fn resolve_annotation(
889 &self,
890 config: &AnnotationConfig<'_>,
891 annotation: Annotation,
892 ) -> Cancellable<Annotation> {
893 self.with_db(|db| annotations::resolve_annotation(db, config, annotation))
894 }
895
896 pub fn move_item(
897 &self,
898 range: FileRange,
899 direction: Direction,
900 ) -> Cancellable<Option<TextEdit>> {
901 self.with_db(|db| move_item::move_item(db, range, direction))
902 }
903
904 pub fn get_recursive_memory_layout(
905 &self,
906 position: FilePosition,
907 ) -> Cancellable<Option<RecursiveMemoryLayout>> {
908 self.with_db(|db| view_memory_layout(db, position))
909 }
910
911 pub fn get_failed_obligations(&self, offset: TextSize, file_id: FileId) -> Cancellable<String> {
912 self.with_db(|db| {
913 let sema = Semantics::new(db);
914 let source_file = sema.parse_guess_edition(file_id);
915
916 let Some(token) = source_file.syntax().token_at_offset(offset).next() else {
917 return String::new();
918 };
919 sema.get_failed_obligations(token).unwrap_or_default()
920 })
921 }
922
923 pub fn editioned_file_id_to_vfs(&self, file_id: hir::EditionedFileId) -> FileId {
924 file_id.file_id(&self.db)
925 }
926
927 fn with_db<F, T>(&self, f: F) -> Cancellable<T>
941 where
942 F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
943 {
944 hir::attach_db_allow_change(&self.db, || Cancelled::catch(|| f(&self.db)))
946 }
947}
948
949#[test]
950fn analysis_is_send() {
951 fn is_send<T: Send>() {}
952 is_send::<Analysis>();
953}