Skip to main content

rust_analyzer/
global_state.rs

1//! The context or environment in which the language server functions. In our
2//! server implementation this is know as the `WorldState`.
3//!
4//! Each tick provides an immutable snapshot of the state as `WorldSnapshot`.
5
6use 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
67// Enforces drop order
68pub(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/// `GlobalState` is the primary mutable state of the language server
77///
78/// The most interesting components are `vfs`, which stores a consistent
79/// snapshot of the file systems, and `analysis_host`, which stores our
80/// incremental salsa database.
81///
82/// Note that this struct has more than one impl in various modules!
83#[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    /// A mapping that maps a local source root's `SourceRootId` to it parent's `SourceRootId`, if it has one.
99    pub(crate) local_roots_parent_map: Arc<FxHashMap<SourceRootId, SourceRootId>>,
100    pub(crate) semantic_tokens_cache: Arc<Mutex<FxHashMap<Uri, SemanticTokens>>>,
101
102    // status
103    pub(crate) shutdown_requested: bool,
104    pub(crate) last_reported_status: lsp_ext::ServerStatusParams,
105
106    /// Clients of the proc-macro server.
107    ///
108    /// One client per workspace, in the same order as `self.workspaces`. We don't store
109    /// the client in `self.workspaces` so that we can reload workspaces without
110    /// restarting the proc-macro server.
111    pub(crate) proc_macro_clients: Arc<[Option<anyhow::Result<ProcMacroClient>>]>,
112
113    pub(crate) build_deps_changed: bool,
114
115    // Flycheck
116    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    // Test explorer
123    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    // Project loading
129    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    // Debouncing channel for fetching the workspace
135    // we want to delay it until the VFS looks stable-ish (and thus is not currently in the middle
136    // of a VCS operation like `git switch`)
137    pub(crate) fetch_ws_receiver: Option<(Receiver<Instant>, FetchWorkspaceRequest)>,
138
139    // VFS
140    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    // used to track how long VFS loading takes. this can't be on `vfs::loader::Handle`,
146    // as that handle's lifetime is the same as `GlobalState` itself.
147    pub(crate) vfs_span: Option<tracing::span::EnteredSpan>,
148    pub(crate) wants_to_switch: Option<Cause>,
149
150    /// `workspaces` field stores the data we actually use, while the `OpQueue`
151    /// stores the result of the last fetch.
152    ///
153    /// If the fetch (partially) fails, we do not update the current value.
154    ///
155    /// The handling of build data is subtle. We fetch workspace in two phases:
156    ///
157    /// *First*, we run `cargo metadata`, which gives us fast results for
158    /// initial analysis.
159    ///
160    /// *Second*, we run `cargo check` which runs build scripts and compiles
161    /// proc macros.
162    ///
163    /// We need both for the precise analysis, but we want rust-analyzer to be
164    /// at least partially available just after the first phase. That's because
165    /// first phase is much faster, and is much less likely to fail.
166    ///
167    /// This creates a complication -- by the time the second phase completes,
168    /// the results of the first phase could be invalid. That is, while we run
169    /// `cargo check`, the user edits `Cargo.toml`, we notice this, and the new
170    /// `cargo metadata` completes before `cargo check`.
171    ///
172    /// An additional complication is that we want to avoid needless work. When
173    /// the user just adds comments or whitespace to Cargo.toml, we do not want
174    /// to invalidate any salsa caches.
175    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    // op queues
180    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    /// A deferred task queue.
186    ///
187    /// This queue is used for doing database-dependent work inside of sync
188    /// handlers, as accessing the database may block latency-sensitive
189    /// interactions and should be moved away from the main thread.
190    ///
191    /// For certain features, such as [`GlobalState::handle_discover_msg`],
192    /// this queue should run only *after* [`GlobalState::process_changes`] has
193    /// been called.
194    pub(crate) deferred_task_queue: DeferredTaskQueue,
195
196    /// HACK: Workaround for <https://github.com/rust-lang/rust-analyzer/issues/19709>
197    /// This is marked true if we failed to load a crate root file at crate graph creation,
198    /// which will usually end up causing a bunch of incorrect diagnostics on startup.
199    pub(crate) incomplete_crate_graph: bool,
200
201    pub(crate) minicore: MiniCoreRustAnalyzerInternalOnly,
202    pub(crate) last_gc_revision: Revision,
203}
204
205// FIXME: This should move to the VFS once the rewrite is done.
206#[derive(Debug, Clone, Default)]
207pub(crate) struct MiniCoreRustAnalyzerInternalOnly {
208    pub(crate) minicore_text: Option<Arc<str>>,
209}
210
211/// An immutable snapshot of the world's state at a point in time.
212pub(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    // used to signal semantic highlighting to fall back to syntax based highlighting until
221    // proc-macros have been loaded
222    // FIXME: Can we derive this from somewhere else?
223    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        // Apply any required database inputs from the config.
334        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        // We cannot directly resolve a change in a ratoml file to a format
341        // that can be used by the config module because config talks
342        // in `SourceRootId`s instead of `FileId`s and `FileId` -> `SourceRootId`
343        // mapping is not ready until `AnalysisHost::apply_changes` has been called.
344        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                // start cancellation in parallel,
357                // allowing us to do meaningful work while waiting
358                let analysis_host = AssertUnwindSafe(&mut self.analysis_host);
359                s.spawn(thread::ThreadIntent::LatencySensitive, || {
360                    { analysis_host }.0.trigger_cancellation()
361                });
362
363                // Allow other readers while we inspect the changes and prepare database inputs.
364                let guard = RwLockWriteGuard::downgrade_to_upgradable(guard);
365                let vfs: &Vfs = &guard.0;
366
367                let mut workspace_structure_change = None;
368                // A file was added or deleted
369                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                        // Remember ids to use them after `apply_changes`
376                        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                    // Clear native diagnostics when their file gets deleted
409                    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                    // Batch `line_endings_map` updates so we can delay upgrading to a write lock.
421                    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                // FIXME @alibektas : This is silly. There is no reason to use VfsPaths when there is SourceRoots. But how
460                // do I resolve a "workspace_root" to its corresponding id without having to rely on a cargo.toml's ( or project json etc.) file id?
461                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                    // If change has been made to a ratoml file that
481                    // belongs to a non-local source root, we will ignore it.
482                    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                            // SourceRoot has more than 1 RATOML files. In this case lexicographically smaller wins.
504                            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                                // Put the old one back in.
509                                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                // No global or client level config was changed. So we can naively replace config.
538                self.config = Arc::new(config);
539            }
540        }
541
542        // FIXME: `workspace_structure_change` is computed from `should_refresh_for_change` which is
543        // path syntax based. That is not sufficient for all cases so we should lift that check out
544        // into a `QueuedTask`, see `handle_did_save_text_document`.
545        // Or maybe instead of replacing that check, kick off a semantic one if the syntactic one
546        // didn't find anything (to make up for the lack of precision).
547        {
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            // FIXME: ideally we should only trigger a workspace fetch for non-library changes
554            // but something's going wrong with the source root business when we add a new local
555            // crate see https://github.com/rust-lang/rust-analyzer/issues/13029
556            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        // We put this on a separate thread to avoid blocking the main thread with serialization work
651        self.task_pool.handle.spawn_with_sender(stdx::thread::ThreadIntent::Worker, {
652            let sender = self.sender.clone();
653            move |_| {
654                // VSCode assumes diagnostic messages to be non-empty strings, so we need to patch
655                // empty diagnostics. Neither the docs of VSCode nor the LSP spec say whether
656                // diagnostic messages are actually allowed to be empty or not and patching this
657                // in the VSCode client does not work as the assertion happens in the protocol
658                // conversion. So this hack is here to stay, and will be considered a hack
659                // until the LSP decides to state that empty messages are allowed.
660
661                // See https://github.com/rust-lang/rust-analyzer/issues/11404
662                // See https://github.com/rust-lang/rust-analyzer/issues/13130
663                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                            // The LSP does not (yet?) specify that related diagnostic messages can
681                            // be in Markdown format (in addition to plain text).
682                            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            // Don't queue up a new fetch request if we already have done so
722            // Otherwise we will re-fetch in quick succession which is unnecessary
723            // Note though, that if one is already in progress, we *want* to re-queue
724            // as the in-progress fetch might not have the latest changes in it anymore
725            // FIXME: We should cancel the in-progress fetch here
726            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    /// Set of crates to prime: the transitive-dependency closure of every
742    /// local Cargo workspace `lib`/`bin` target, `rust-project.json` workspace
743    /// member, and detached file. Computed once when the server becomes
744    /// quiescent.
745    ///
746    /// Test, example, and benchmark members are deliberately excluded — they're
747    /// leaves, so not priming them costs no parallelism on dependency work.
748    /// `bin` targets are kept because they're the crate the user is most likely
749    /// editing.
750    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        // Map each crate-root path to its crate(s) so target roots resolve to
755        // `Crate` ids. The vfs read lock is held only for this build.
756        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    /// Returns `None` if the file was excluded.
823    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    /// Returns `None` if the file was excluded.
832    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
983/// Returns `None` if the file was excluded.
984pub(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
989/// Returns `None` if the file was excluded.
990pub(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}