]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/global_state.rs
Merge #10211
[rust.git] / crates / rust-analyzer / src / 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
6 use std::{sync::Arc, time::Instant};
7
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::ProcMacroServer;
15 use project_model::{CargoWorkspace, ProjectWorkspace, Target, WorkspaceBuildScripts};
16 use rustc_hash::FxHashMap;
17 use vfs::AnchoredPathBuf;
18
19 use crate::{
20     config::Config,
21     diagnostics::{CheckFixes, DiagnosticCollection},
22     from_proto,
23     line_index::{LineEndings, LineIndex},
24     lsp_ext,
25     main_loop::Task,
26     mem_docs::MemDocs,
27     op_queue::OpQueue,
28     reload::{self, SourceRootConfig},
29     thread_pool::TaskPool,
30     to_proto::url_from_abs_path,
31     Result,
32 };
33
34 // Enforces drop order
35 pub(crate) struct Handle<H, C> {
36     pub(crate) handle: H,
37     pub(crate) receiver: C,
38 }
39
40 pub(crate) type ReqHandler = fn(&mut GlobalState, lsp_server::Response);
41 pub(crate) type ReqQueue = lsp_server::ReqQueue<(String, Instant), ReqHandler>;
42
43 /// `GlobalState` is the primary mutable state of the language server
44 ///
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.
48 ///
49 /// Note that this struct has more than on impl in various modules!
50 pub(crate) struct GlobalState {
51     sender: Sender<lsp_server::Message>,
52     req_queue: ReqQueue,
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<ProcMacroServer>,
64
65     pub(crate) flycheck: Vec<FlycheckHandle>,
66     pub(crate) flycheck_sender: Sender<flycheck::Message>,
67     pub(crate) flycheck_receiver: Receiver<flycheck::Message>,
68
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,
74
75     /// `workspaces` field stores the data we actually use, while the `OpQueue`
76     /// stores the result of the last fetch.
77     ///
78     /// If the fetch (partially) fails, we do not update the current value.
79     ///
80     /// The handling of build data is subtle. We fetch workspace in two phases:
81     ///
82     /// *First*, we run `cargo metadata`, which gives us fast results for
83     /// initial analysis.
84     ///
85     /// *Second*, we run `cargo check` which runs build scripts and compiles
86     /// proc macros.
87     ///
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.
91     ///
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`.
96     ///
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>>)>,
104
105     pub(crate) prime_caches_queue: OpQueue<()>,
106 }
107
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,
113     mem_docs: MemDocs,
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>>,
117 }
118
119 impl std::panic::UnwindSafe for GlobalStateSnapshot {}
120
121 impl GlobalState {
122     pub(crate) fn new(sender: Sender<lsp_server::Message>, config: Config) -> GlobalState {
123         let loader = {
124             let (sender, receiver) = unbounded::<vfs::loader::Message>();
125             let handle: vfs_notify::NotifyHandle =
126                 vfs::loader::Handle::spawn(Box::new(move |msg| sender.send(msg).unwrap()));
127             let handle = Box::new(handle) as Box<dyn vfs::loader::Handle>;
128             Handle { handle, receiver }
129         };
130
131         let task_pool = {
132             let (sender, receiver) = unbounded();
133             let handle = TaskPool::new(sender);
134             Handle { handle, receiver }
135         };
136
137         let analysis_host = AnalysisHost::new(config.lru_capacity());
138         let (flycheck_sender, flycheck_receiver) = unbounded();
139         let mut this = GlobalState {
140             sender,
141             req_queue: ReqQueue::default(),
142             task_pool,
143             loader,
144             config: Arc::new(config.clone()),
145             analysis_host,
146             diagnostics: Default::default(),
147             mem_docs: MemDocs::default(),
148             semantic_tokens_cache: Arc::new(Default::default()),
149             shutdown_requested: false,
150             last_reported_status: None,
151             source_root_config: SourceRootConfig::default(),
152             proc_macro_client: None,
153
154             flycheck: Vec::new(),
155             flycheck_sender,
156             flycheck_receiver,
157
158             vfs: Arc::new(RwLock::new((vfs::Vfs::default(), FxHashMap::default()))),
159             vfs_config_version: 0,
160             vfs_progress_config_version: 0,
161             vfs_progress_n_total: 0,
162             vfs_progress_n_done: 0,
163
164             workspaces: Arc::new(Vec::new()),
165             fetch_workspaces_queue: OpQueue::default(),
166             prime_caches_queue: OpQueue::default(),
167
168             fetch_build_data_queue: OpQueue::default(),
169         };
170         // Apply any required database inputs from the config.
171         this.update_configuration(config);
172         this
173     }
174
175     pub(crate) fn process_changes(&mut self) -> bool {
176         let _p = profile::span("GlobalState::process_changes");
177         let mut fs_changes = Vec::new();
178         // A file was added or deleted
179         let mut has_structure_changes = false;
180
181         let change = {
182             let mut change = Change::new();
183             let (vfs, line_endings_map) = &mut *self.vfs.write();
184             let changed_files = vfs.take_changes();
185             if changed_files.is_empty() {
186                 return false;
187             }
188
189             for file in changed_files {
190                 if let Some(path) = vfs.file_path(file.file_id).as_path() {
191                     let path = path.to_path_buf();
192                     if reload::should_refresh_for_change(&path, file.change_kind) {
193                         self.fetch_workspaces_queue.request_op();
194                     }
195                     fs_changes.push((path, file.change_kind));
196                     if file.is_created_or_deleted() {
197                         has_structure_changes = true;
198                     }
199                 }
200
201                 let text = if file.exists() {
202                     let bytes = vfs.file_contents(file.file_id).to_vec();
203                     match String::from_utf8(bytes).ok() {
204                         Some(text) => {
205                             let (text, line_endings) = LineEndings::normalize(text);
206                             line_endings_map.insert(file.file_id, line_endings);
207                             Some(Arc::new(text))
208                         }
209                         None => None,
210                     }
211                 } else {
212                     None
213                 };
214                 change.change_file(file.file_id, text);
215             }
216             if has_structure_changes {
217                 let roots = self.source_root_config.partition(vfs);
218                 change.set_roots(roots);
219             }
220             change
221         };
222
223         self.analysis_host.apply_change(change);
224         true
225     }
226
227     pub(crate) fn snapshot(&self) -> GlobalStateSnapshot {
228         GlobalStateSnapshot {
229             config: Arc::clone(&self.config),
230             workspaces: Arc::clone(&self.workspaces),
231             analysis: self.analysis_host.analysis(),
232             vfs: Arc::clone(&self.vfs),
233             check_fixes: Arc::clone(&self.diagnostics.check_fixes),
234             mem_docs: self.mem_docs.clone(),
235             semantic_tokens_cache: Arc::clone(&self.semantic_tokens_cache),
236         }
237     }
238
239     pub(crate) fn send_request<R: lsp_types::request::Request>(
240         &mut self,
241         params: R::Params,
242         handler: ReqHandler,
243     ) {
244         let request = self.req_queue.outgoing.register(R::METHOD.to_string(), params, handler);
245         self.send(request.into());
246     }
247     pub(crate) fn complete_request(&mut self, response: lsp_server::Response) {
248         let handler = self.req_queue.outgoing.complete(response.id.clone());
249         handler(self, response)
250     }
251
252     pub(crate) fn send_notification<N: lsp_types::notification::Notification>(
253         &mut self,
254         params: N::Params,
255     ) {
256         let not = lsp_server::Notification::new(N::METHOD.to_string(), params);
257         self.send(not.into());
258     }
259
260     pub(crate) fn register_request(
261         &mut self,
262         request: &lsp_server::Request,
263         request_received: Instant,
264     ) {
265         self.req_queue
266             .incoming
267             .register(request.id.clone(), (request.method.clone(), request_received));
268     }
269     pub(crate) fn respond(&mut self, response: lsp_server::Response) {
270         if let Some((method, start)) = self.req_queue.incoming.complete(response.id.clone()) {
271             if let Some(err) = &response.error {
272                 if err.message.starts_with("server panicked") {
273                     self.poke_rust_analyzer_developer(format!("{}, check the log", err.message))
274                 }
275             }
276
277             let duration = start.elapsed();
278             tracing::info!("handled {} - ({}) in {:0.2?}", method, response.id, duration);
279             self.send(response.into());
280         }
281     }
282     pub(crate) fn cancel(&mut self, request_id: lsp_server::RequestId) {
283         if let Some(response) = self.req_queue.incoming.cancel(request_id) {
284             self.send(response.into());
285         }
286     }
287
288     fn send(&mut self, message: lsp_server::Message) {
289         self.sender.send(message).unwrap()
290     }
291 }
292
293 impl Drop for GlobalState {
294     fn drop(&mut self) {
295         self.analysis_host.request_cancellation()
296     }
297 }
298
299 impl GlobalStateSnapshot {
300     pub(crate) fn url_to_file_id(&self, url: &Url) -> Result<FileId> {
301         url_to_file_id(&self.vfs.read().0, url)
302     }
303
304     pub(crate) fn file_id_to_url(&self, id: FileId) -> Url {
305         file_id_to_url(&self.vfs.read().0, id)
306     }
307
308     pub(crate) fn file_line_index(&self, file_id: FileId) -> Cancellable<LineIndex> {
309         let endings = self.vfs.read().1[&file_id];
310         let index = self.analysis.file_line_index(file_id)?;
311         let res = LineIndex { index, endings, encoding: self.config.offset_encoding() };
312         Ok(res)
313     }
314
315     pub(crate) fn url_file_version(&self, url: &Url) -> Option<i32> {
316         let path = from_proto::vfs_path(url).ok()?;
317         Some(self.mem_docs.get(&path)?.version)
318     }
319
320     pub(crate) fn anchored_path(&self, path: &AnchoredPathBuf) -> Url {
321         let mut base = self.vfs.read().0.file_path(path.anchor);
322         base.pop();
323         let path = base.join(&path.path).unwrap();
324         let path = path.as_path().unwrap();
325         url_from_abs_path(path)
326     }
327
328     pub(crate) fn cargo_target_for_crate_root(
329         &self,
330         crate_id: CrateId,
331     ) -> Option<(&CargoWorkspace, Target)> {
332         let file_id = self.analysis.crate_root(crate_id).ok()?;
333         let path = self.vfs.read().0.file_path(file_id);
334         let path = path.as_path()?;
335         self.workspaces.iter().find_map(|ws| match ws {
336             ProjectWorkspace::Cargo { cargo, .. } => {
337                 cargo.target_by_root(path).map(|it| (cargo, it))
338             }
339             ProjectWorkspace::Json { .. } => None,
340             ProjectWorkspace::DetachedFiles { .. } => None,
341         })
342     }
343 }
344
345 pub(crate) fn file_id_to_url(vfs: &vfs::Vfs, id: FileId) -> Url {
346     let path = vfs.file_path(id);
347     let path = path.as_path().unwrap();
348     url_from_abs_path(path)
349 }
350
351 pub(crate) fn url_to_file_id(vfs: &vfs::Vfs, url: &Url) -> Result<FileId> {
352     let path = from_proto::vfs_path(url)?;
353     let res = vfs.file_id(&path).ok_or_else(|| format!("file not found: {}", path))?;
354     Ok(res)
355 }