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