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