1use std::{
7 ops::Not as _,
8 panic::AssertUnwindSafe,
9 time::{Duration, Instant},
10};
11
12use crossbeam_channel::{Receiver, Sender, unbounded};
13use hir::ChangeWithProcMacros;
14use ide::{Analysis, AnalysisHost, Cancellable, FileId, SourceRootId};
15use ide_db::{
16 MiniCore,
17 base_db::{Crate, ProcMacroPaths, SourceDatabase, TargetKind, all_crates, salsa::Revision},
18};
19use itertools::Itertools;
20use load_cargo::SourceRootConfig;
21use lsp_types::{Notification, SemanticTokens, Uri};
22use parking_lot::{
23 MappedRwLockReadGuard, Mutex, RwLock, RwLockReadGuard, RwLockUpgradableReadGuard,
24 RwLockWriteGuard,
25};
26use proc_macro_api::client::ProcMacroClient;
27use project_model::{ManifestPath, ProjectWorkspace, ProjectWorkspaceKind, WorkspaceBuildScripts};
28use rustc_hash::{FxHashMap, FxHashSet};
29use stdx::thread;
30use tracing::{Level, span, trace};
31use triomphe::Arc;
32use vfs::{AbsPathBuf, AnchoredPathBuf, ChangeKind, LineEndings, Vfs, VfsPath};
33
34use crate::{
35 config::{Config, ConfigChange, ConfigErrors, RatomlFileKind},
36 diagnostics::{CheckFixes, DiagnosticCollection},
37 discover,
38 flycheck::{FlycheckHandle, FlycheckMessage, PackageSpecifier},
39 line_index::LineIndex,
40 lsp::{from_proto, to_proto::url_from_abs_path},
41 lsp_ext,
42 main_loop::Task,
43 mem_docs::MemDocs,
44 op_queue::{Cause, OpQueue},
45 priming_scope, reload,
46 target_spec::{CargoTargetSpec, ProjectJsonTargetSpec, TargetSpec},
47 task_pool::{DeferredTaskQueue, TaskPool},
48 test_runner::{CargoTestHandle, CargoTestMessage},
49};
50
51#[derive(Debug)]
52pub(crate) struct FetchWorkspaceRequest {
53 pub(crate) path: Option<AbsPathBuf>,
54 pub(crate) force_crate_graph_reload: bool,
55}
56
57pub(crate) struct FetchWorkspaceResponse {
58 pub(crate) workspaces: Vec<anyhow::Result<ProjectWorkspace>>,
59 pub(crate) force_crate_graph_reload: bool,
60}
61
62pub(crate) struct FetchBuildDataResponse {
63 pub(crate) workspaces: Arc<Vec<ProjectWorkspace>>,
64 pub(crate) build_scripts: Vec<anyhow::Result<WorkspaceBuildScripts>>,
65}
66
67pub(crate) struct Handle<H, C> {
69 pub(crate) handle: H,
70 pub(crate) receiver: C,
71}
72
73pub(crate) type ReqHandler = fn(&mut GlobalState, lsp_server::Response);
74type ReqQueue = lsp_server::ReqQueue<(String, Instant), ReqHandler>;
75
76#[doc(alias = "GlobalMess")]
84pub(crate) struct GlobalState {
85 sender: Sender<lsp_server::Message>,
86 req_queue: ReqQueue,
87
88 pub(crate) task_pool: Handle<TaskPool<Task>, Receiver<Task>>,
89 pub(crate) fmt_pool: Handle<TaskPool<Task>, Receiver<Task>>,
90 pub(crate) cancellation_pool: thread::Pool,
91
92 pub(crate) config: Arc<Config>,
93 pub(crate) config_errors: Option<ConfigErrors>,
94 pub(crate) analysis_host: AnalysisHost,
95 pub(crate) diagnostics: DiagnosticCollection,
96 pub(crate) mem_docs: MemDocs,
97 pub(crate) source_root_config: SourceRootConfig,
98 pub(crate) local_roots_parent_map: Arc<FxHashMap<SourceRootId, SourceRootId>>,
100 pub(crate) semantic_tokens_cache: Arc<Mutex<FxHashMap<Uri, SemanticTokens>>>,
101
102 pub(crate) shutdown_requested: bool,
104 pub(crate) last_reported_status: lsp_ext::ServerStatusParams,
105
106 pub(crate) proc_macro_clients: Arc<[Option<anyhow::Result<ProcMacroClient>>]>,
112
113 pub(crate) build_deps_changed: bool,
114
115 pub(crate) flycheck: Arc<[FlycheckHandle]>,
117 pub(crate) flycheck_sender: Sender<FlycheckMessage>,
118 pub(crate) flycheck_receiver: Receiver<FlycheckMessage>,
119 pub(crate) last_flycheck_error: Option<String>,
120 pub(crate) flycheck_formatted_commands: Vec<String>,
121
122 pub(crate) test_run_session: Option<Vec<CargoTestHandle>>,
124 pub(crate) test_run_sender: Sender<CargoTestMessage>,
125 pub(crate) test_run_receiver: Receiver<CargoTestMessage>,
126 pub(crate) test_run_remaining_jobs: usize,
127
128 pub(crate) discover_handles: Vec<discover::DiscoverHandle>,
130 pub(crate) discover_sender: Sender<discover::DiscoverProjectMessage>,
131 pub(crate) discover_receiver: Receiver<discover::DiscoverProjectMessage>,
132 pub(crate) discover_jobs_active: u32,
133
134 pub(crate) fetch_ws_receiver: Option<(Receiver<Instant>, FetchWorkspaceRequest)>,
138
139 pub(crate) loader: Handle<Box<dyn vfs::loader::Handle>, Receiver<vfs::loader::Message>>,
141 pub(crate) vfs: Arc<RwLock<(vfs::Vfs, FxHashMap<FileId, LineEndings>)>>,
142 pub(crate) vfs_config_version: u32,
143 pub(crate) vfs_progress_config_version: u32,
144 pub(crate) vfs_done: bool,
145 pub(crate) vfs_span: Option<tracing::span::EnteredSpan>,
148 pub(crate) wants_to_switch: Option<Cause>,
149
150 pub(crate) workspaces: Arc<Vec<ProjectWorkspace>>,
176 pub(crate) crate_graph_file_dependencies: FxHashSet<vfs::VfsPath>,
177 pub(crate) detached_files: FxHashSet<ManifestPath>,
178
179 pub(crate) fetch_workspaces_queue: OpQueue<FetchWorkspaceRequest, FetchWorkspaceResponse>,
181 pub(crate) fetch_build_data_queue: OpQueue<(), FetchBuildDataResponse>,
182 pub(crate) fetch_proc_macros_queue: OpQueue<(ChangeWithProcMacros, Vec<ProcMacroPaths>), bool>,
183 pub(crate) prime_caches_queue: OpQueue,
184
185 pub(crate) deferred_task_queue: DeferredTaskQueue,
195
196 pub(crate) incomplete_crate_graph: bool,
200
201 pub(crate) minicore: MiniCoreRustAnalyzerInternalOnly,
202 pub(crate) last_gc_revision: Revision,
203}
204
205#[derive(Debug, Clone, Default)]
207pub(crate) struct MiniCoreRustAnalyzerInternalOnly {
208 pub(crate) minicore_text: Option<Arc<str>>,
209}
210
211pub(crate) struct GlobalStateSnapshot {
213 pub(crate) config: Arc<Config>,
214 pub(crate) analysis: Analysis,
215 pub(crate) check_fixes: CheckFixes,
216 mem_docs: MemDocs,
217 pub(crate) semantic_tokens_cache: Arc<Mutex<FxHashMap<Uri, SemanticTokens>>>,
218 vfs: Arc<RwLock<(vfs::Vfs, FxHashMap<FileId, LineEndings>)>>,
219 pub(crate) workspaces: Arc<Vec<ProjectWorkspace>>,
220 pub(crate) proc_macros_loaded: bool,
224 pub(crate) flycheck: Arc<[FlycheckHandle]>,
225 minicore: MiniCoreRustAnalyzerInternalOnly,
226}
227
228impl std::panic::UnwindSafe for GlobalStateSnapshot {}
229
230impl GlobalState {
231 pub(crate) fn new(sender: Sender<lsp_server::Message>, config: Config) -> GlobalState {
232 let loader = {
233 let (sender, receiver) = unbounded::<vfs::loader::Message>();
234 let handle: vfs_notify::NotifyHandle = vfs::loader::Handle::spawn(sender);
235 let handle = Box::new(handle) as Box<dyn vfs::loader::Handle>;
236 Handle { handle, receiver }
237 };
238
239 let task_pool = {
240 let (sender, receiver) = unbounded();
241 let handle = TaskPool::new_with_threads(sender, config.main_loop_num_threads());
242 Handle { handle, receiver }
243 };
244 let fmt_pool = {
245 let (sender, receiver) = unbounded();
246 let handle = TaskPool::new_with_threads(sender, 1);
247 Handle { handle, receiver }
248 };
249 let cancellation_pool = thread::Pool::new(1);
250
251 let deferred_task_queue = {
252 let (sender, receiver) = unbounded();
253 DeferredTaskQueue { sender, receiver }
254 };
255
256 let mut analysis_host = AnalysisHost::new(config.lru_parse_query_capacity());
257 if let Some(capacities) = config.lru_query_capacities_config() {
258 analysis_host.update_lru_capacities(capacities);
259 }
260 let (flycheck_sender, flycheck_receiver) = unbounded();
261 let (test_run_sender, test_run_receiver) = unbounded();
262
263 let (discover_sender, discover_receiver) = unbounded();
264
265 let last_gc_revision = analysis_host.raw_database().nonce_and_revision().1;
266
267 let mut this = GlobalState {
268 sender,
269 req_queue: ReqQueue::default(),
270 task_pool,
271 fmt_pool,
272 cancellation_pool,
273 loader,
274 config: Arc::new(config.clone()),
275 analysis_host,
276 diagnostics: Default::default(),
277 mem_docs: MemDocs::default(),
278 semantic_tokens_cache: Arc::new(Default::default()),
279 shutdown_requested: false,
280 last_reported_status: lsp_ext::ServerStatusParams {
281 health: lsp_ext::Health::Ok,
282 quiescent: true,
283 message: None,
284 },
285 source_root_config: SourceRootConfig::default(),
286 local_roots_parent_map: Arc::new(FxHashMap::default()),
287 config_errors: Default::default(),
288
289 proc_macro_clients: Arc::from_iter([]),
290
291 build_deps_changed: false,
292
293 flycheck: Arc::from_iter([]),
294 flycheck_sender,
295 flycheck_receiver,
296 last_flycheck_error: None,
297 flycheck_formatted_commands: vec![],
298
299 test_run_session: None,
300 test_run_sender,
301 test_run_receiver,
302 test_run_remaining_jobs: 0,
303
304 discover_handles: vec![],
305 discover_sender,
306 discover_receiver,
307 discover_jobs_active: 0,
308
309 fetch_ws_receiver: None,
310
311 vfs: Arc::new(RwLock::new((vfs::Vfs::default(), Default::default()))),
312 vfs_config_version: 0,
313 vfs_progress_config_version: 0,
314 vfs_span: None,
315 vfs_done: true,
316 wants_to_switch: None,
317
318 workspaces: Arc::from(Vec::new()),
319 crate_graph_file_dependencies: FxHashSet::default(),
320 detached_files: FxHashSet::default(),
321 fetch_workspaces_queue: OpQueue::default(),
322 fetch_build_data_queue: OpQueue::default(),
323 fetch_proc_macros_queue: OpQueue::default(),
324
325 prime_caches_queue: OpQueue::default(),
326
327 deferred_task_queue,
328 incomplete_crate_graph: false,
329
330 minicore: MiniCoreRustAnalyzerInternalOnly::default(),
331 last_gc_revision,
332 };
333 this.update_configuration(config);
335 this
336 }
337
338 pub(crate) fn process_changes(&mut self) -> (bool, Option<Duration>) {
339 let _p = span!(Level::INFO, "GlobalState::process_changes").entered();
340 let mut modified_ratoml_files: FxHashMap<FileId, (ChangeKind, vfs::VfsPath)> =
345 FxHashMap::default();
346
347 let mut change = ChangeWithProcMacros::default();
348 let mut guard = self.vfs.write();
349 let changed_files = guard.0.take_changes();
350 if changed_files.is_empty() {
351 return (false, None);
352 }
353
354 let (change, modified_rust_files, workspace_structure_change) =
355 self.cancellation_pool.scoped(|s| {
356 let analysis_host = AssertUnwindSafe(&mut self.analysis_host);
359 s.spawn(thread::ThreadIntent::LatencySensitive, || {
360 { analysis_host }.0.trigger_cancellation()
361 });
362
363 let guard = RwLockWriteGuard::downgrade_to_upgradable(guard);
365 let vfs: &Vfs = &guard.0;
366
367 let mut workspace_structure_change = None;
368 let mut has_structure_changes = false;
370 let mut bytes = vec![];
371 let mut modified_rust_files = vec![];
372 for file in changed_files.into_values() {
373 let vfs_path = vfs.file_path(file.file_id);
374 if let Some(("rust-analyzer", Some("toml"))) = vfs_path.name_and_extension() {
375 modified_ratoml_files.insert(file.file_id, (file.kind(), vfs_path.clone()));
377 }
378
379 if let Some(path) = vfs_path.as_path() {
380 has_structure_changes |= file.is_created_or_deleted();
381
382 if file.is_modified() && path.extension() == Some("rs") {
383 modified_rust_files.push(file.file_id);
384 }
385
386 let additional_files = self
387 .config
388 .discover_workspace_config()
389 .map(|cfg| {
390 cfg.files_to_watch.iter().map(String::as_str).collect::<Vec<&str>>()
391 })
392 .unwrap_or_default();
393
394 let path = path.to_path_buf();
395 if file.is_created_or_deleted() {
396 workspace_structure_change.get_or_insert((path, false)).1 |=
397 self.crate_graph_file_dependencies.contains(vfs_path);
398 } else if reload::should_refresh_for_change(
399 &path,
400 file.kind(),
401 &additional_files,
402 ) {
403 trace!(?path, kind = ?file.kind(), "refreshing for a change");
404 workspace_structure_change.get_or_insert((path.clone(), false));
405 }
406 }
407
408 if !file.exists() {
410 self.diagnostics.clear_native_for(file.file_id);
411 }
412
413 let text = match file.change {
414 vfs::Change::Create(vfs::FileContents::Text { text, line_endings }, _)
415 | vfs::Change::Modify(vfs::FileContents::Text { text, line_endings }, _) => {
416 Some((text, line_endings))
417 }
418 _ => None,
419 };
420 bytes.push((file.file_id, text));
422 }
423 let (vfs, line_endings_map) = &mut *RwLockUpgradableReadGuard::upgrade(guard);
424 bytes.into_iter().for_each(|(file_id, text)| {
425 let text = match text {
426 None => None,
427 Some((text, line_endings)) => {
428 line_endings_map.insert(file_id, line_endings);
429 Some(text)
430 }
431 };
432 change.change_file(file_id, text);
433 });
434 if has_structure_changes {
435 let roots = self.source_root_config.partition(vfs);
436 change.set_roots(roots);
437 }
438 (change, modified_rust_files, workspace_structure_change)
439 });
440
441 let cancellation_time = self.analysis_host.apply_change(change);
442
443 if !modified_ratoml_files.is_empty()
444 || !self.config.same_source_root_parent_map(&self.local_roots_parent_map)
445 {
446 let config_change = {
447 let _p = span!(Level::INFO, "GlobalState::process_changes/config_change").entered();
448 let user_config_path = (|| {
449 let mut p = Config::user_config_dir_path()?;
450 p.push("rust-analyzer.toml");
451 Some(p)
452 })();
453
454 let user_config_abs_path = user_config_path.as_deref();
455
456 let mut change = ConfigChange::default();
457 let db = self.analysis_host.raw_database();
458
459 let workspace_ratoml_paths = self
462 .workspaces
463 .iter()
464 .map(|ws| {
465 VfsPath::from({
466 let mut p = ws.workspace_root().to_owned();
467 p.push("rust-analyzer.toml");
468 p
469 })
470 })
471 .collect_vec();
472
473 for (file_id, (change_kind, vfs_path)) in modified_ratoml_files {
474 tracing::info!(%vfs_path, ?change_kind, "Processing rust-analyzer.toml changes");
475 if vfs_path.as_path() == user_config_abs_path {
476 tracing::info!(%vfs_path, ?change_kind, "Use config rust-analyzer.toml changes");
477 change.change_user_config(Some(db.file_text(file_id).text(db).clone()));
478 }
479
480 let source_root_id = db.file_source_root(file_id).source_root_id(db);
483 let source_root = db.source_root(source_root_id).source_root(db);
484
485 if !source_root.is_library {
486 let entry = if workspace_ratoml_paths.contains(&vfs_path) {
487 tracing::info!(%vfs_path, ?source_root_id, "workspace rust-analyzer.toml changes");
488 change.change_workspace_ratoml(
489 source_root_id,
490 vfs_path.clone(),
491 Some(db.file_text(file_id).text(db).clone()),
492 )
493 } else {
494 tracing::info!(%vfs_path, ?source_root_id, "crate rust-analyzer.toml changes");
495 change.change_ratoml(
496 source_root_id,
497 vfs_path.clone(),
498 Some(db.file_text(file_id).text(db).clone()),
499 )
500 };
501
502 if let Some((kind, old_path, old_text)) = entry {
503 if old_path < vfs_path {
505 tracing::error!(
506 "Two `rust-analyzer.toml` files were found inside the same crate. {vfs_path} has no effect."
507 );
508 match kind {
510 RatomlFileKind::Crate => {
511 change.change_ratoml(source_root_id, old_path, old_text);
512 }
513 RatomlFileKind::Workspace => {
514 change.change_workspace_ratoml(
515 source_root_id,
516 old_path,
517 old_text,
518 );
519 }
520 }
521 }
522 }
523 } else {
524 tracing::info!(%vfs_path, "Ignoring library rust-analyzer.toml");
525 }
526 }
527 change.change_source_root_parent_map(self.local_roots_parent_map.clone());
528 change
529 };
530
531 let (config, e, should_update) = self.config.apply_change(config_change);
532 self.config_errors = e.is_empty().not().then_some(e);
533
534 if should_update {
535 self.update_configuration(config);
536 } else {
537 self.config = Arc::new(config);
539 }
540 }
541
542 {
548 if !matches!(&workspace_structure_change, Some((.., true))) {
549 _ = self.deferred_task_queue.sender.send(
550 crate::main_loop::DeferredTask::CheckProcMacroSources(modified_rust_files),
551 );
552 }
553 if let Some((path, force_crate_graph_reload)) = workspace_structure_change {
557 let _p = span!(Level::INFO, "GlobalState::process_changes/ws_structure_change")
558 .entered();
559 self.enqueue_workspace_fetch(path, force_crate_graph_reload);
560 }
561 }
562
563 (true, Some(cancellation_time))
564 }
565
566 pub(crate) fn snapshot(&self) -> GlobalStateSnapshot {
567 GlobalStateSnapshot {
568 config: Arc::clone(&self.config),
569 workspaces: Arc::clone(&self.workspaces),
570 analysis: self.analysis_host.analysis(),
571 vfs: Arc::clone(&self.vfs),
572 minicore: self.minicore.clone(),
573 check_fixes: Arc::clone(&self.diagnostics.check_fixes),
574 mem_docs: self.mem_docs.clone(),
575 semantic_tokens_cache: Arc::clone(&self.semantic_tokens_cache),
576 proc_macros_loaded: !self.config.expand_proc_macros()
577 || self.fetch_proc_macros_queue.last_op_result().copied().unwrap_or(false),
578 flycheck: self.flycheck.clone(),
579 }
580 }
581
582 pub(crate) fn send_request<R: lsp_types::Request>(
583 &mut self,
584 params: R::Params,
585 handler: ReqHandler,
586 ) {
587 let request = self.req_queue.outgoing.register(R::METHOD.into(), params, handler);
588 self.send(request.into());
589 }
590
591 pub(crate) fn complete_request(&mut self, response: lsp_server::Response) {
592 let handler = self
593 .req_queue
594 .outgoing
595 .complete(response.id.clone())
596 .expect("received response for unknown request");
597 handler(self, response)
598 }
599
600 pub(crate) fn send_notification<N: lsp_types::Notification>(&self, params: N::Params) {
601 let not = lsp_server::Notification::new(N::METHOD.into(), params);
602 self.send(not.into());
603 }
604
605 pub(crate) fn register_request(
606 &mut self,
607 request: &lsp_server::Request,
608 request_received: Instant,
609 ) {
610 self.req_queue
611 .incoming
612 .register(request.id.clone(), (request.method.clone(), request_received));
613 }
614
615 pub(crate) fn respond(&mut self, response: lsp_server::Response) {
616 if let Some((method, start)) = self.req_queue.incoming.complete(&response.id) {
617 if let Some(err) = &response.error
618 && err.message.starts_with("server panicked")
619 {
620 self.poke_rust_analyzer_developer(format!("{}, check the log", err.message));
621 }
622
623 let duration = start.elapsed();
624 tracing::debug!(name: "message response", method, %response.id, duration = format_args!("{:0.2?}", duration));
625 self.send(response.into());
626 }
627 }
628
629 pub(crate) fn cancel(&mut self, request_id: lsp_server::RequestId) {
630 if let Some(response) = self.req_queue.incoming.cancel(request_id) {
631 self.send(response.into());
632 }
633 }
634
635 pub(crate) fn is_completed(&self, request: &lsp_server::Request) -> bool {
636 self.req_queue.incoming.is_completed(&request.id)
637 }
638
639 #[track_caller]
640 fn send(&self, message: lsp_server::Message) {
641 self.sender.send(message).unwrap();
642 }
643
644 pub(crate) fn publish_diagnostics(
645 &mut self,
646 uri: Uri,
647 version: Option<i32>,
648 mut diagnostics: Vec<lsp_types::Diagnostic>,
649 ) {
650 self.task_pool.handle.spawn_with_sender(stdx::thread::ThreadIntent::Worker, {
652 let sender = self.sender.clone();
653 move |_| {
654 let patch_empty = |message: &mut lsp_types::Message| match message {
664 lsp_types::Message::String(m) if m.is_empty() => {
665 " ".clone_into(m);
666 }
667 lsp_types::Message::MarkupContent(lsp_types::MarkupContent {
668 value,
669 kind: _,
670 }) if value.is_empty() => {
671 " ".clone_into(value);
672 }
673 _ => {}
674 };
675
676 for d in &mut diagnostics {
677 patch_empty(&mut d.message);
678 if let Some(dri) = &mut d.related_information {
679 for dri in dri {
680 if dri.message.is_empty() {
683 " ".clone_into(&mut dri.message);
684 }
685 }
686 }
687 }
688
689 let not = lsp_server::Notification::new(
690 lsp_types::PublishDiagnosticsNotification::METHOD.into(),
691 lsp_types::PublishDiagnosticsParams { uri, diagnostics, version },
692 );
693 _ = sender.send(not.into());
694 }
695 });
696 }
697
698 pub(crate) fn check_workspaces_msrv(&self) -> impl Iterator<Item = String> + '_ {
699 self.workspaces.iter().filter_map(|ws| {
700 if let Some(toolchain) = &ws.toolchain
701 && *toolchain < crate::MINIMUM_SUPPORTED_TOOLCHAIN_VERSION
702 {
703 return Some(format!(
704 "Workspace `{}` is using an outdated toolchain version `{}` but \
705 rust-analyzer only supports `{}` and higher.\n\
706 Consider using the rust-analyzer rustup component for your toolchain or
707 upgrade your toolchain to a supported version.\n\n",
708 ws.manifest_or_root(),
709 toolchain,
710 crate::MINIMUM_SUPPORTED_TOOLCHAIN_VERSION,
711 ));
712 }
713 None
714 })
715 }
716
717 fn enqueue_workspace_fetch(&mut self, path: AbsPathBuf, force_crate_graph_reload: bool) {
718 let already_requested = self.fetch_workspaces_queue.op_requested()
719 && !self.fetch_workspaces_queue.op_in_progress();
720 if self.fetch_ws_receiver.is_none() && already_requested {
721 return;
727 }
728
729 self.fetch_ws_receiver = Some((
730 crossbeam_channel::after(Duration::from_millis(100)),
731 FetchWorkspaceRequest { path: Some(path), force_crate_graph_reload },
732 ));
733 }
734
735 pub(crate) fn debounce_workspace_fetch(&mut self) {
736 if let Some((fetch_receiver, _)) = &mut self.fetch_ws_receiver {
737 *fetch_receiver = crossbeam_channel::after(Duration::from_millis(100));
738 }
739 }
740
741 pub(crate) fn compute_priming_scope(&self) -> Arc<[Crate]> {
751 let db = self.analysis_host.raw_database();
752 let all = all_crates(db);
753
754 let root_to_crate: FxHashMap<AbsPathBuf, Vec<Crate>> = {
757 let vfs = self.vfs.read();
758 let mut root_to_crate: FxHashMap<AbsPathBuf, Vec<Crate>> = FxHashMap::default();
759 for &krate in &*all {
760 let root_file = krate.data(db).root_file_id;
761 let path = vfs.0.file_path(root_file);
762 let Some(path) = path.as_path() else {
763 continue;
764 };
765 root_to_crate.entry(path.to_path_buf()).or_default().push(krate);
766 }
767 root_to_crate
768 };
769
770 let mut seed: FxHashSet<Crate> = FxHashSet::default();
771 for workspace in self.workspaces.iter() {
772 match &workspace.kind {
773 ProjectWorkspaceKind::Cargo { cargo, .. }
774 | ProjectWorkspaceKind::DetachedFile { cargo: Some((cargo, ..)), .. } => {
775 for pkg in cargo.packages() {
776 if !cargo[pkg].is_local {
777 continue;
778 }
779 for &target in &cargo[pkg].targets {
780 if !matches!(
781 cargo[target].kind,
782 TargetKind::Lib { .. } | TargetKind::Bin
783 ) {
784 continue;
785 }
786 if let Some(krates) = root_to_crate.get(&*cargo[target].root) {
787 seed.extend(krates.iter().copied());
788 }
789 }
790 }
791 }
792 ProjectWorkspaceKind::Json(project_json) => seed.extend(
793 project_json
794 .crates()
795 .filter(|(_, krate)| krate.is_workspace_member)
796 .filter_map(|(_, krate)| root_to_crate.get(&krate.root_module))
797 .flat_map(|it| it.iter().copied()),
798 ),
799 ProjectWorkspaceKind::DetachedFile { file, cargo: None } => {
800 if let Some(krates) = root_to_crate.get(&**file) {
801 seed.extend(krates.iter().copied());
802 }
803 }
804 }
805 }
806
807 priming_scope::compute(db, seed)
808 }
809}
810
811impl Drop for GlobalState {
812 fn drop(&mut self) {
813 self.analysis_host.trigger_cancellation();
814 }
815}
816
817impl GlobalStateSnapshot {
818 fn vfs_read(&self) -> MappedRwLockReadGuard<'_, vfs::Vfs> {
819 RwLockReadGuard::map(self.vfs.read(), |(it, _)| it)
820 }
821
822 pub(crate) fn url_to_file_id(&self, url: &Uri) -> anyhow::Result<Option<FileId>> {
824 url_to_file_id(&self.vfs_read(), url)
825 }
826
827 pub(crate) fn file_id_to_url(&self, id: FileId) -> Uri {
828 file_id_to_url(&self.vfs_read(), id)
829 }
830
831 pub(crate) fn vfs_path_to_file_id(&self, vfs_path: &VfsPath) -> anyhow::Result<Option<FileId>> {
833 vfs_path_to_file_id(&self.vfs_read(), vfs_path)
834 }
835
836 pub(crate) fn file_line_index(&self, file_id: FileId) -> Cancellable<LineIndex> {
837 let endings = self.vfs.read().1[&file_id];
838 let index = self.analysis.file_line_index(file_id)?;
839 let res = LineIndex { index, endings, encoding: self.config.caps().negotiated_encoding() };
840 Ok(res)
841 }
842
843 pub(crate) fn file_version(&self, file_id: FileId) -> Option<i32> {
844 Some(self.mem_docs.get(self.vfs_read().file_path(file_id))?.version)
845 }
846
847 pub(crate) fn url_file_version(&self, url: &Uri) -> Option<i32> {
848 let path = from_proto::vfs_path(url).ok()?;
849 Some(self.mem_docs.get(&path)?.version)
850 }
851
852 pub(crate) fn anchored_path(&self, path: &AnchoredPathBuf) -> Uri {
853 let mut base = self.vfs_read().file_path(path.anchor).clone();
854 base.pop();
855 let path = base.join(&path.path).unwrap();
856 let path = path.as_path().unwrap();
857 url_from_abs_path(path)
858 }
859
860 pub(crate) fn file_id_to_file_path(&self, file_id: FileId) -> vfs::VfsPath {
861 self.vfs_read().file_path(file_id).clone()
862 }
863
864 pub(crate) fn target_spec_for_crate(&self, crate_id: Crate) -> Option<TargetSpec> {
865 let file_id = self.analysis.crate_root(crate_id).ok()?;
866 self.target_spec_for_file(file_id, crate_id)
867 }
868
869 pub(crate) fn target_spec_for_file(
870 &self,
871 file_id: FileId,
872 crate_id: Crate,
873 ) -> Option<TargetSpec> {
874 let path = self.vfs_read().file_path(file_id).clone();
875 let path = path.as_path()?;
876
877 for workspace in self.workspaces.iter() {
878 match &workspace.kind {
879 ProjectWorkspaceKind::Cargo { cargo, .. }
880 | ProjectWorkspaceKind::DetachedFile { cargo: Some((cargo, _, _)), .. } => {
881 let Some(target_idx) = cargo.target_by_root(path) else {
882 continue;
883 };
884
885 let target_data = &cargo[target_idx];
886 let package_data = &cargo[target_data.package];
887
888 return Some(TargetSpec::Cargo(CargoTargetSpec {
889 workspace_root: cargo.workspace_root().to_path_buf(),
890 cargo_toml: package_data.manifest.clone(),
891 crate_id,
892 package: cargo.package_flag(package_data),
893 package_id: package_data.id.clone(),
894 target: target_data.name.clone(),
895 target_kind: target_data.kind,
896 required_features: target_data.required_features.clone(),
897 features: package_data.features.keys().cloned().collect(),
898 sysroot_root: workspace.sysroot.root().map(ToOwned::to_owned),
899 }));
900 }
901 ProjectWorkspaceKind::Json(project) => {
902 let Some(krate) = project.crate_by_root(path) else {
903 continue;
904 };
905 let Some(build) = krate.build.clone() else {
906 continue;
907 };
908
909 return Some(TargetSpec::ProjectJson(ProjectJsonTargetSpec {
910 label: build.label,
911 target_kind: build.target_kind,
912 shell_runnables: project.runnables().to_owned(),
913 project_root: project.project_root().to_owned(),
914 }));
915 }
916 ProjectWorkspaceKind::DetachedFile { .. } => {}
917 };
918 }
919
920 None
921 }
922
923 pub(crate) fn all_workspace_dependencies_for_package(
924 &self,
925 package: &PackageSpecifier,
926 ) -> Option<FxHashSet<PackageSpecifier>> {
927 match package {
928 PackageSpecifier::Cargo { package_id } => {
929 self.workspaces.iter().find_map(|workspace| match &workspace.kind {
930 ProjectWorkspaceKind::Cargo { cargo, .. }
931 | ProjectWorkspaceKind::DetachedFile { cargo: Some((cargo, _, _)), .. } => {
932 let package = cargo.packages().find(|p| cargo[*p].id == *package_id)?;
933
934 cargo[package].all_member_deps.as_ref().map(|deps| {
935 deps.iter()
936 .map(|dep| cargo[*dep].id.clone())
937 .map(|p| PackageSpecifier::Cargo { package_id: p })
938 .collect()
939 })
940 }
941 _ => None,
942 })
943 }
944 PackageSpecifier::BuildInfo { label } => {
945 self.workspaces.iter().find_map(|workspace| match &workspace.kind {
946 ProjectWorkspaceKind::Json(p) => {
947 let krate = p.crate_by_label(label)?;
948 Some(
949 krate
950 .iter_deps()
951 .filter_map(|dep| p[dep].build.as_ref())
952 .map(|build| PackageSpecifier::BuildInfo {
953 label: build.label.clone(),
954 })
955 .collect(),
956 )
957 }
958 _ => None,
959 })
960 }
961 }
962 }
963
964 pub(crate) fn file_exists(&self, file_id: FileId) -> bool {
965 self.vfs.read().0.exists(file_id)
966 }
967
968 #[inline]
969 pub(crate) fn minicore(&self) -> MiniCore<'_> {
970 match &self.minicore.minicore_text {
971 Some(minicore) => MiniCore::new(minicore),
972 None => MiniCore::default(),
973 }
974 }
975}
976
977pub(crate) fn file_id_to_url(vfs: &vfs::Vfs, id: FileId) -> Uri {
978 let path = vfs.file_path(id);
979 let path = path.as_path().unwrap();
980 url_from_abs_path(path)
981}
982
983pub(crate) fn url_to_file_id(vfs: &vfs::Vfs, url: &Uri) -> anyhow::Result<Option<FileId>> {
985 let path = from_proto::vfs_path(url)?;
986 vfs_path_to_file_id(vfs, &path)
987}
988
989pub(crate) fn vfs_path_to_file_id(
991 vfs: &vfs::Vfs,
992 vfs_path: &VfsPath,
993) -> anyhow::Result<Option<FileId>> {
994 let (file_id, excluded) =
995 vfs.file_id(vfs_path).ok_or_else(|| anyhow::format_err!("file not found: {vfs_path}"))?;
996 match excluded {
997 vfs::FileExcluded::Yes => Ok(None),
998 vfs::FileExcluded::No => Ok(Some(file_id)),
999 }
1000}