1 //! The context or environment in which the language server functions. In our
2 //! server implementation this is know as the `WorldState`.
4 //! Each tick provides an immutable snapshot of the state as `WorldSnapshot`.
6 use std::{sync::Arc, time::Instant};
8 use crossbeam_channel::{unbounded, Receiver, Sender};
9 use flycheck::FlycheckHandle;
10 use ide::{Analysis, AnalysisHost, Cancellable, Change, FileId};
11 use ide_db::base_db::{CrateId, FileLoader, SourceDatabase};
12 use lsp_types::{SemanticTokens, Url};
13 use parking_lot::{Mutex, RwLock};
14 use proc_macro_api::ProcMacroServer;
15 use project_model::{CargoWorkspace, ProjectWorkspace, Target, WorkspaceBuildScripts};
16 use rustc_hash::FxHashMap;
17 use stdx::hash::NoHashHashMap;
18 use vfs::AnchoredPathBuf;
22 diagnostics::{CheckFixes, DiagnosticCollection},
24 line_index::{LineEndings, LineIndex},
29 reload::{self, SourceRootConfig},
31 to_proto::url_from_abs_path,
35 // Enforces drop order
36 pub(crate) struct Handle<H, C> {
38 pub(crate) receiver: C,
41 pub(crate) type ReqHandler = fn(&mut GlobalState, lsp_server::Response);
42 pub(crate) type ReqQueue = lsp_server::ReqQueue<(String, Instant), ReqHandler>;
44 /// `GlobalState` is the primary mutable state of the language server
46 /// The most interesting components are `vfs`, which stores a consistent
47 /// snapshot of the file systems, and `analysis_host`, which stores our
48 /// incremental salsa database.
50 /// Note that this struct has more than one impl in various modules!
51 pub(crate) struct GlobalState {
52 sender: Sender<lsp_server::Message>,
54 pub(crate) task_pool: Handle<TaskPool<Task>, Receiver<Task>>,
55 pub(crate) loader: Handle<Box<dyn vfs::loader::Handle>, Receiver<vfs::loader::Message>>,
56 pub(crate) config: Arc<Config>,
57 pub(crate) analysis_host: AnalysisHost,
58 pub(crate) diagnostics: DiagnosticCollection,
59 pub(crate) mem_docs: MemDocs,
60 pub(crate) semantic_tokens_cache: Arc<Mutex<FxHashMap<Url, SemanticTokens>>>,
61 pub(crate) shutdown_requested: bool,
62 pub(crate) proc_macro_changed: bool,
63 pub(crate) last_reported_status: Option<lsp_ext::ServerStatusParams>,
64 pub(crate) source_root_config: SourceRootConfig,
65 pub(crate) proc_macro_clients: Vec<Result<ProcMacroServer, String>>,
67 pub(crate) flycheck: Vec<FlycheckHandle>,
68 pub(crate) flycheck_sender: Sender<flycheck::Message>,
69 pub(crate) flycheck_receiver: Receiver<flycheck::Message>,
71 pub(crate) vfs: Arc<RwLock<(vfs::Vfs, NoHashHashMap<FileId, LineEndings>)>>,
72 pub(crate) vfs_config_version: u32,
73 pub(crate) vfs_progress_config_version: u32,
74 pub(crate) vfs_progress_n_total: usize,
75 pub(crate) vfs_progress_n_done: usize,
77 /// `workspaces` field stores the data we actually use, while the `OpQueue`
78 /// stores the result of the last fetch.
80 /// If the fetch (partially) fails, we do not update the current value.
82 /// The handling of build data is subtle. We fetch workspace in two phases:
84 /// *First*, we run `cargo metadata`, which gives us fast results for
87 /// *Second*, we run `cargo check` which runs build scripts and compiles
90 /// We need both for the precise analysis, but we want rust-analyzer to be
91 /// at least partially available just after the first phase. That's because
92 /// first phase is much faster, and is much less likely to fail.
94 /// This creates a complication -- by the time the second phase completes,
95 /// the results of the fist phase could be invalid. That is, while we run
96 /// `cargo check`, the user edits `Cargo.toml`, we notice this, and the new
97 /// `cargo metadata` completes before `cargo check`.
99 /// An additional complication is that we want to avoid needless work. When
100 /// the user just adds comments or whitespace to Cargo.toml, we do not want
101 /// to invalidate any salsa caches.
102 pub(crate) workspaces: Arc<Vec<ProjectWorkspace>>,
103 pub(crate) fetch_workspaces_queue: OpQueue<Vec<anyhow::Result<ProjectWorkspace>>>,
104 pub(crate) fetch_build_data_queue:
105 OpQueue<(Arc<Vec<ProjectWorkspace>>, Vec<anyhow::Result<WorkspaceBuildScripts>>)>,
107 pub(crate) prime_caches_queue: OpQueue<()>,
110 /// An immutable snapshot of the world's state at a point in time.
111 pub(crate) struct GlobalStateSnapshot {
112 pub(crate) config: Arc<Config>,
113 pub(crate) analysis: Analysis,
114 pub(crate) check_fixes: CheckFixes,
116 pub(crate) semantic_tokens_cache: Arc<Mutex<FxHashMap<Url, SemanticTokens>>>,
117 vfs: Arc<RwLock<(vfs::Vfs, NoHashHashMap<FileId, LineEndings>)>>,
118 pub(crate) workspaces: Arc<Vec<ProjectWorkspace>>,
119 pub(crate) proc_macros_loaded: bool,
122 impl std::panic::UnwindSafe for GlobalStateSnapshot {}
125 pub(crate) fn new(sender: Sender<lsp_server::Message>, config: Config) -> GlobalState {
127 let (sender, receiver) = unbounded::<vfs::loader::Message>();
128 let handle: vfs_notify::NotifyHandle =
129 vfs::loader::Handle::spawn(Box::new(move |msg| sender.send(msg).unwrap()));
130 let handle = Box::new(handle) as Box<dyn vfs::loader::Handle>;
131 Handle { handle, receiver }
135 let (sender, receiver) = unbounded();
136 let handle = TaskPool::new(sender);
137 Handle { handle, receiver }
140 let analysis_host = AnalysisHost::new(config.lru_capacity());
141 let (flycheck_sender, flycheck_receiver) = unbounded();
142 let mut this = GlobalState {
144 req_queue: ReqQueue::default(),
147 config: Arc::new(config.clone()),
149 diagnostics: Default::default(),
150 mem_docs: MemDocs::default(),
151 semantic_tokens_cache: Arc::new(Default::default()),
152 shutdown_requested: false,
153 proc_macro_changed: false,
154 last_reported_status: None,
155 source_root_config: SourceRootConfig::default(),
156 proc_macro_clients: vec![],
158 flycheck: Vec::new(),
162 vfs: Arc::new(RwLock::new((vfs::Vfs::default(), NoHashHashMap::default()))),
163 vfs_config_version: 0,
164 vfs_progress_config_version: 0,
165 vfs_progress_n_total: 0,
166 vfs_progress_n_done: 0,
168 workspaces: Arc::new(Vec::new()),
169 fetch_workspaces_queue: OpQueue::default(),
170 prime_caches_queue: OpQueue::default(),
172 fetch_build_data_queue: OpQueue::default(),
174 // Apply any required database inputs from the config.
175 this.update_configuration(config);
179 pub(crate) fn process_changes(&mut self) -> bool {
180 let _p = profile::span("GlobalState::process_changes");
181 // A file was added or deleted
182 let mut has_structure_changes = false;
183 let mut workspace_structure_change = None;
185 let (change, changed_files) = {
186 let mut change = Change::new();
187 let (vfs, line_endings_map) = &mut *self.vfs.write();
188 let changed_files = vfs.take_changes();
189 if changed_files.is_empty() {
193 for file in &changed_files {
194 if let Some(path) = vfs.file_path(file.file_id).as_path() {
195 let path = path.to_path_buf();
196 if reload::should_refresh_for_change(&path, file.change_kind) {
197 workspace_structure_change = Some(path);
199 if file.is_created_or_deleted() {
200 has_structure_changes = true;
204 // Clear native diagnostics when their file gets deleted
206 self.diagnostics.clear_native_for(file.file_id);
209 let text = if file.exists() {
210 let bytes = vfs.file_contents(file.file_id).to_vec();
211 String::from_utf8(bytes).ok().and_then(|text| {
212 let (text, line_endings) = LineEndings::normalize(text);
213 line_endings_map.insert(file.file_id, line_endings);
219 change.change_file(file.file_id, text);
221 if has_structure_changes {
222 let roots = self.source_root_config.partition(vfs);
223 change.set_roots(roots);
225 (change, changed_files)
228 self.analysis_host.apply_change(change);
231 let raw_database = self.analysis_host.raw_database();
232 // FIXME: ideally we should only trigger a workspace fetch for non-library changes
233 // but somethings going wrong with the source root business when we add a new local
234 // crate see https://github.com/rust-lang/rust-analyzer/issues/13029
235 if let Some(path) = workspace_structure_change {
236 self.fetch_workspaces_queue
237 .request_op(format!("workspace vfs file change: {}", path.display()));
239 self.proc_macro_changed =
240 changed_files.iter().filter(|file| !file.is_created_or_deleted()).any(|file| {
241 let crates = raw_database.relevant_crates(file.file_id);
242 let crate_graph = raw_database.crate_graph();
244 crates.iter().any(|&krate| crate_graph[krate].is_proc_macro)
251 pub(crate) fn snapshot(&self) -> GlobalStateSnapshot {
252 GlobalStateSnapshot {
253 config: Arc::clone(&self.config),
254 workspaces: Arc::clone(&self.workspaces),
255 analysis: self.analysis_host.analysis(),
256 vfs: Arc::clone(&self.vfs),
257 check_fixes: Arc::clone(&self.diagnostics.check_fixes),
258 mem_docs: self.mem_docs.clone(),
259 semantic_tokens_cache: Arc::clone(&self.semantic_tokens_cache),
260 proc_macros_loaded: !self.fetch_build_data_queue.last_op_result().0.is_empty(),
264 pub(crate) fn send_request<R: lsp_types::request::Request>(
269 let request = self.req_queue.outgoing.register(R::METHOD.to_string(), params, handler);
270 self.send(request.into());
273 pub(crate) fn complete_request(&mut self, response: lsp_server::Response) {
277 .complete(response.id.clone())
278 .expect("received response for unknown request");
279 handler(self, response)
282 pub(crate) fn send_notification<N: lsp_types::notification::Notification>(
286 let not = lsp_server::Notification::new(N::METHOD.to_string(), params);
287 self.send(not.into());
290 pub(crate) fn register_request(
292 request: &lsp_server::Request,
293 request_received: Instant,
297 .register(request.id.clone(), (request.method.clone(), request_received));
300 pub(crate) fn respond(&mut self, response: lsp_server::Response) {
301 if let Some((method, start)) = self.req_queue.incoming.complete(response.id.clone()) {
302 if let Some(err) = &response.error {
303 if err.message.starts_with("server panicked") {
304 self.poke_rust_analyzer_developer(format!("{}, check the log", err.message))
308 let duration = start.elapsed();
309 tracing::debug!("handled {} - ({}) in {:0.2?}", method, response.id, duration);
310 self.send(response.into());
314 pub(crate) fn cancel(&mut self, request_id: lsp_server::RequestId) {
315 if let Some(response) = self.req_queue.incoming.cancel(request_id) {
316 self.send(response.into());
320 fn send(&mut self, message: lsp_server::Message) {
321 self.sender.send(message).unwrap()
325 impl Drop for GlobalState {
327 self.analysis_host.request_cancellation();
331 impl GlobalStateSnapshot {
332 pub(crate) fn url_to_file_id(&self, url: &Url) -> Result<FileId> {
333 url_to_file_id(&self.vfs.read().0, url)
336 pub(crate) fn file_id_to_url(&self, id: FileId) -> Url {
337 file_id_to_url(&self.vfs.read().0, id)
340 pub(crate) fn file_line_index(&self, file_id: FileId) -> Cancellable<LineIndex> {
341 let endings = self.vfs.read().1[&file_id];
342 let index = self.analysis.file_line_index(file_id)?;
343 let res = LineIndex { index, endings, encoding: self.config.offset_encoding() };
347 pub(crate) fn url_file_version(&self, url: &Url) -> Option<i32> {
348 let path = from_proto::vfs_path(url).ok()?;
349 Some(self.mem_docs.get(&path)?.version)
352 pub(crate) fn anchored_path(&self, path: &AnchoredPathBuf) -> Url {
353 let mut base = self.vfs.read().0.file_path(path.anchor);
355 let path = base.join(&path.path).unwrap();
356 let path = path.as_path().unwrap();
357 url_from_abs_path(path)
360 pub(crate) fn cargo_target_for_crate_root(
363 ) -> Option<(&CargoWorkspace, Target)> {
364 let file_id = self.analysis.crate_root(crate_id).ok()?;
365 let path = self.vfs.read().0.file_path(file_id);
366 let path = path.as_path()?;
367 self.workspaces.iter().find_map(|ws| match ws {
368 ProjectWorkspace::Cargo { cargo, .. } => {
369 cargo.target_by_root(path).map(|it| (cargo, it))
371 ProjectWorkspace::Json { .. } => None,
372 ProjectWorkspace::DetachedFiles { .. } => None,
377 pub(crate) fn file_id_to_url(vfs: &vfs::Vfs, id: FileId) -> Url {
378 let path = vfs.file_path(id);
379 let path = path.as_path().unwrap();
380 url_from_abs_path(path)
383 pub(crate) fn url_to_file_id(vfs: &vfs::Vfs, url: &Url) -> Result<FileId> {
384 let path = from_proto::vfs_path(url)?;
385 let res = vfs.file_id(&path).ok_or_else(|| format!("file not found: {}", path))?;