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;
12 use lsp_types::{SemanticTokens, Url};
13 use parking_lot::{Mutex, RwLock};
14 use proc_macro_api::ProcMacroClient;
15 use project_model::{CargoWorkspace, ProjectWorkspace, Target, WorkspaceBuildScripts};
16 use rustc_hash::FxHashMap;
17 use vfs::AnchoredPathBuf;
21 diagnostics::{CheckFixes, DiagnosticCollection},
23 line_index::{LineEndings, LineIndex},
28 reload::SourceRootConfig,
29 thread_pool::TaskPool,
30 to_proto::url_from_abs_path,
34 // Enforces drop order
35 pub(crate) struct Handle<H, C> {
37 pub(crate) receiver: C,
40 pub(crate) type ReqHandler = fn(&mut GlobalState, lsp_server::Response);
41 pub(crate) type ReqQueue = lsp_server::ReqQueue<(String, Instant), ReqHandler>;
43 /// `GlobalState` is the primary mutable state of the language server
45 /// The most interesting components are `vfs`, which stores a consistent
46 /// snapshot of the file systems, and `analysis_host`, which stores our
47 /// incremental salsa database.
49 /// Note that this struct has more than on impl in various modules!
50 pub(crate) struct GlobalState {
51 sender: Sender<lsp_server::Message>,
53 pub(crate) task_pool: Handle<TaskPool<Task>, Receiver<Task>>,
54 pub(crate) loader: Handle<Box<dyn vfs::loader::Handle>, Receiver<vfs::loader::Message>>,
55 pub(crate) config: Arc<Config>,
56 pub(crate) analysis_host: AnalysisHost,
57 pub(crate) diagnostics: DiagnosticCollection,
58 pub(crate) mem_docs: MemDocs,
59 pub(crate) semantic_tokens_cache: Arc<Mutex<FxHashMap<Url, SemanticTokens>>>,
60 pub(crate) shutdown_requested: bool,
61 pub(crate) last_reported_status: Option<lsp_ext::ServerStatusParams>,
62 pub(crate) source_root_config: SourceRootConfig,
63 pub(crate) proc_macro_client: Option<ProcMacroClient>,
65 pub(crate) flycheck: Vec<FlycheckHandle>,
66 pub(crate) flycheck_sender: Sender<flycheck::Message>,
67 pub(crate) flycheck_receiver: Receiver<flycheck::Message>,
69 pub(crate) vfs: Arc<RwLock<(vfs::Vfs, FxHashMap<FileId, LineEndings>)>>,
70 pub(crate) vfs_config_version: u32,
71 pub(crate) vfs_progress_config_version: u32,
72 pub(crate) vfs_progress_n_total: usize,
73 pub(crate) vfs_progress_n_done: usize,
75 /// `workspaces` field stores the data we actually use, while the `OpQueue`
76 /// stores the result of the last fetch.
78 /// If the fetch (partially) fails, we do not update the current value.
80 /// The handling of build data is subtle. We fetch workspace in two phases:
82 /// *First*, we run `cargo metadata`, which gives us fast results for
85 /// *Second*, we run `cargo check` which runs build scripts and compiles
88 /// We need both for the precise analysis, but we want rust-analyzer to be
89 /// at least partially available just after the first phase. That's because
90 /// first phase is much faster, and is much less likely to fail.
92 /// This creates a complication -- by the time the second phase completes,
93 /// the results of the fist phase could be invalid. That is, while we run
94 /// `cargo check`, the user edits `Cargo.toml`, we notice this, and the new
95 /// `cargo metadata` completes before `cargo check`.
97 /// An additional complication is that we want to avoid needless work. When
98 /// the user just adds comments or whitespace to Cargo.toml, we do not want
99 /// to invalidate any salsa caches.
100 pub(crate) workspaces: Arc<Vec<ProjectWorkspace>>,
101 pub(crate) fetch_workspaces_queue: OpQueue<Vec<anyhow::Result<ProjectWorkspace>>>,
102 pub(crate) fetch_build_data_queue:
103 OpQueue<(Arc<Vec<ProjectWorkspace>>, Vec<anyhow::Result<WorkspaceBuildScripts>>)>,
105 pub(crate) prime_caches_queue: OpQueue<()>,
108 /// An immutable snapshot of the world's state at a point in time.
109 pub(crate) struct GlobalStateSnapshot {
110 pub(crate) config: Arc<Config>,
111 pub(crate) analysis: Analysis,
112 pub(crate) check_fixes: CheckFixes,
114 pub(crate) semantic_tokens_cache: Arc<Mutex<FxHashMap<Url, SemanticTokens>>>,
115 vfs: Arc<RwLock<(vfs::Vfs, FxHashMap<FileId, LineEndings>)>>,
116 pub(crate) workspaces: Arc<Vec<ProjectWorkspace>>,
120 pub(crate) fn new(sender: Sender<lsp_server::Message>, config: Config) -> GlobalState {
122 let (sender, receiver) = unbounded::<vfs::loader::Message>();
123 let handle: vfs_notify::NotifyHandle =
124 vfs::loader::Handle::spawn(Box::new(move |msg| sender.send(msg).unwrap()));
125 let handle = Box::new(handle) as Box<dyn vfs::loader::Handle>;
126 Handle { handle, receiver }
130 let (sender, receiver) = unbounded();
131 let handle = TaskPool::new(sender);
132 Handle { handle, receiver }
135 let analysis_host = AnalysisHost::new(config.lru_capacity());
136 let (flycheck_sender, flycheck_receiver) = unbounded();
137 let mut this = GlobalState {
139 req_queue: ReqQueue::default(),
142 config: Arc::new(config.clone()),
144 diagnostics: Default::default(),
145 mem_docs: MemDocs::default(),
146 semantic_tokens_cache: Arc::new(Default::default()),
147 shutdown_requested: false,
148 last_reported_status: None,
149 source_root_config: SourceRootConfig::default(),
150 proc_macro_client: None,
152 flycheck: Vec::new(),
156 vfs: Arc::new(RwLock::new((vfs::Vfs::default(), FxHashMap::default()))),
157 vfs_config_version: 0,
158 vfs_progress_config_version: 0,
159 vfs_progress_n_total: 0,
160 vfs_progress_n_done: 0,
162 workspaces: Arc::new(Vec::new()),
163 fetch_workspaces_queue: OpQueue::default(),
164 prime_caches_queue: OpQueue::default(),
166 fetch_build_data_queue: OpQueue::default(),
168 // Apply any required database inputs from the config.
169 this.update_configuration(config);
173 pub(crate) fn process_changes(&mut self) -> bool {
174 let _p = profile::span("GlobalState::process_changes");
175 let mut fs_changes = Vec::new();
176 let mut has_fs_changes = false;
179 let mut change = Change::new();
180 let (vfs, line_endings_map) = &mut *self.vfs.write();
181 let changed_files = vfs.take_changes();
182 if changed_files.is_empty() {
186 for file in changed_files {
187 if file.is_created_or_deleted() {
188 if let Some(path) = vfs.file_path(file.file_id).as_path() {
189 fs_changes.push((path.to_path_buf(), file.change_kind));
190 has_fs_changes = true;
194 let text = if file.exists() {
195 let bytes = vfs.file_contents(file.file_id).to_vec();
196 match String::from_utf8(bytes).ok() {
198 let (text, line_endings) = LineEndings::normalize(text);
199 line_endings_map.insert(file.file_id, line_endings);
207 change.change_file(file.file_id, text);
210 let roots = self.source_root_config.partition(vfs);
211 change.set_roots(roots);
216 self.analysis_host.apply_change(change);
217 self.maybe_refresh(&fs_changes);
221 pub(crate) fn snapshot(&self) -> GlobalStateSnapshot {
222 GlobalStateSnapshot {
223 config: Arc::clone(&self.config),
224 workspaces: Arc::clone(&self.workspaces),
225 analysis: self.analysis_host.analysis(),
226 vfs: Arc::clone(&self.vfs),
227 check_fixes: Arc::clone(&self.diagnostics.check_fixes),
228 mem_docs: self.mem_docs.clone(),
229 semantic_tokens_cache: Arc::clone(&self.semantic_tokens_cache),
233 pub(crate) fn send_request<R: lsp_types::request::Request>(
238 let request = self.req_queue.outgoing.register(R::METHOD.to_string(), params, handler);
239 self.send(request.into());
241 pub(crate) fn complete_request(&mut self, response: lsp_server::Response) {
242 let handler = self.req_queue.outgoing.complete(response.id.clone());
243 handler(self, response)
246 pub(crate) fn send_notification<N: lsp_types::notification::Notification>(
250 let not = lsp_server::Notification::new(N::METHOD.to_string(), params);
251 self.send(not.into());
254 pub(crate) fn register_request(
256 request: &lsp_server::Request,
257 request_received: Instant,
261 .register(request.id.clone(), (request.method.clone(), request_received));
263 pub(crate) fn respond(&mut self, response: lsp_server::Response) {
264 if let Some((method, start)) = self.req_queue.incoming.complete(response.id.clone()) {
265 let duration = start.elapsed();
266 log::info!("handled {} - ({}) in {:0.2?}", method, response.id, duration);
267 self.send(response.into());
270 pub(crate) fn cancel(&mut self, request_id: lsp_server::RequestId) {
271 if let Some(response) = self.req_queue.incoming.cancel(request_id) {
272 self.send(response.into());
276 fn send(&mut self, message: lsp_server::Message) {
277 self.sender.send(message).unwrap()
281 impl Drop for GlobalState {
283 self.analysis_host.request_cancellation()
287 impl GlobalStateSnapshot {
288 pub(crate) fn url_to_file_id(&self, url: &Url) -> Result<FileId> {
289 url_to_file_id(&self.vfs.read().0, url)
292 pub(crate) fn file_id_to_url(&self, id: FileId) -> Url {
293 file_id_to_url(&self.vfs.read().0, id)
296 pub(crate) fn file_line_index(&self, file_id: FileId) -> Cancellable<LineIndex> {
297 let endings = self.vfs.read().1[&file_id];
298 let index = self.analysis.file_line_index(file_id)?;
299 let res = LineIndex { index, endings, encoding: self.config.offset_encoding() };
303 pub(crate) fn url_file_version(&self, url: &Url) -> Option<i32> {
304 let path = from_proto::vfs_path(url).ok()?;
305 Some(self.mem_docs.get(&path)?.version)
308 pub(crate) fn anchored_path(&self, path: &AnchoredPathBuf) -> Url {
309 let mut base = self.vfs.read().0.file_path(path.anchor);
311 let path = base.join(&path.path).unwrap();
312 let path = path.as_path().unwrap();
313 url_from_abs_path(path)
316 pub(crate) fn cargo_target_for_crate_root(
319 ) -> Option<(&CargoWorkspace, Target)> {
320 let file_id = self.analysis.crate_root(crate_id).ok()?;
321 let path = self.vfs.read().0.file_path(file_id);
322 let path = path.as_path()?;
323 self.workspaces.iter().find_map(|ws| match ws {
324 ProjectWorkspace::Cargo { cargo, .. } => {
325 cargo.target_by_root(path).map(|it| (cargo, it))
327 ProjectWorkspace::Json { .. } => None,
328 ProjectWorkspace::DetachedFiles { .. } => None,
333 pub(crate) fn file_id_to_url(vfs: &vfs::Vfs, id: FileId) -> Url {
334 let path = vfs.file_path(id);
335 let path = path.as_path().unwrap();
336 url_from_abs_path(path)
339 pub(crate) fn url_to_file_id(vfs: &vfs::Vfs, url: &Url) -> Result<FileId> {
340 let path = from_proto::vfs_path(url)?;
341 let res = vfs.file_id(&path).ok_or_else(|| format!("file not found: {}", path))?;