]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/global_state.rs
internal: prepare to track changes to mem_docs
[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     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: MemDocs,
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     /// `workspaces` field stores the data we actually use, while the `OpQueue`
78     /// stores the result of the last fetch.
79     ///
80     /// If the fetch (partially) fails, we do not update the current value.
81     ///
82     /// The handling of build data is subtle. We fetch workspace in two phases:
83     ///
84     /// *First*, we run `cargo metadata`, which gives us fast results for
85     /// initial analysis.
86     ///
87     /// *Second*, we run `cargo check` which runs build scripts and compiles
88     /// proc macros.
89     ///
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.
93     ///
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`.
98     ///
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>>)>,
106
107     pub(crate) prime_caches_queue: OpQueue<()>,
108
109     latest_requests: Arc<RwLock<LatestRequests>>,
110 }
111
112 /// An immutable snapshot of the world's state at a point in time.
113 pub(crate) struct GlobalStateSnapshot {
114     pub(crate) config: Arc<Config>,
115     pub(crate) analysis: Analysis,
116     pub(crate) check_fixes: CheckFixes,
117     pub(crate) latest_requests: Arc<RwLock<LatestRequests>>,
118     mem_docs: MemDocs,
119     pub(crate) semantic_tokens_cache: Arc<Mutex<FxHashMap<Url, SemanticTokens>>>,
120     vfs: Arc<RwLock<(vfs::Vfs, FxHashMap<FileId, LineEndings>)>>,
121     pub(crate) workspaces: Arc<Vec<ProjectWorkspace>>,
122 }
123
124 impl GlobalState {
125     pub(crate) fn new(sender: Sender<lsp_server::Message>, config: Config) -> GlobalState {
126         let loader = {
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 }
132         };
133
134         let task_pool = {
135             let (sender, receiver) = unbounded();
136             let handle = TaskPool::new(sender);
137             Handle { handle, receiver }
138         };
139
140         let analysis_host = AnalysisHost::new(config.lru_capacity());
141         let (flycheck_sender, flycheck_receiver) = unbounded();
142         let mut this = GlobalState {
143             sender,
144             req_queue: ReqQueue::default(),
145             task_pool,
146             loader,
147             config: Arc::new(config.clone()),
148             analysis_host,
149             diagnostics: Default::default(),
150             mem_docs: MemDocs::default(),
151             semantic_tokens_cache: Arc::new(Default::default()),
152             shutdown_requested: false,
153             last_reported_status: None,
154             source_root_config: SourceRootConfig::default(),
155             proc_macro_client: None,
156
157             flycheck: Vec::new(),
158             flycheck_sender,
159             flycheck_receiver,
160
161             vfs: Arc::new(RwLock::new((vfs::Vfs::default(), FxHashMap::default()))),
162             vfs_config_version: 0,
163             vfs_progress_config_version: 0,
164             vfs_progress_n_total: 0,
165             vfs_progress_n_done: 0,
166
167             workspaces: Arc::new(Vec::new()),
168             fetch_workspaces_queue: OpQueue::default(),
169             prime_caches_queue: OpQueue::default(),
170
171             fetch_build_data_queue: OpQueue::default(),
172             latest_requests: Default::default(),
173         };
174         // Apply any required database inputs from the config.
175         this.update_configuration(config);
176         this
177     }
178
179     pub(crate) fn process_changes(&mut self) -> bool {
180         let _p = profile::span("GlobalState::process_changes");
181         let mut fs_changes = Vec::new();
182         let mut has_fs_changes = false;
183
184         let change = {
185             let mut change = Change::new();
186             let (vfs, line_endings_map) = &mut *self.vfs.write();
187             let changed_files = vfs.take_changes();
188             if changed_files.is_empty() {
189                 return false;
190             }
191
192             for file in changed_files {
193                 if file.is_created_or_deleted() {
194                     if let Some(path) = vfs.file_path(file.file_id).as_path() {
195                         fs_changes.push((path.to_path_buf(), file.change_kind));
196                         has_fs_changes = true;
197                     }
198                 }
199
200                 let text = if file.exists() {
201                     let bytes = vfs.file_contents(file.file_id).to_vec();
202                     match String::from_utf8(bytes).ok() {
203                         Some(text) => {
204                             let (text, line_endings) = LineEndings::normalize(text);
205                             line_endings_map.insert(file.file_id, line_endings);
206                             Some(Arc::new(text))
207                         }
208                         None => None,
209                     }
210                 } else {
211                     None
212                 };
213                 change.change_file(file.file_id, text);
214             }
215             if has_fs_changes {
216                 let roots = self.source_root_config.partition(vfs);
217                 change.set_roots(roots);
218             }
219             change
220         };
221
222         self.analysis_host.apply_change(change);
223         self.maybe_refresh(&fs_changes);
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             latest_requests: Arc::clone(&self.latest_requests),
234             check_fixes: Arc::clone(&self.diagnostics.check_fixes),
235             mem_docs: self.mem_docs.clone(),
236             semantic_tokens_cache: Arc::clone(&self.semantic_tokens_cache),
237         }
238     }
239
240     pub(crate) fn send_request<R: lsp_types::request::Request>(
241         &mut self,
242         params: R::Params,
243         handler: ReqHandler,
244     ) {
245         let request = self.req_queue.outgoing.register(R::METHOD.to_string(), params, handler);
246         self.send(request.into());
247     }
248     pub(crate) fn complete_request(&mut self, response: lsp_server::Response) {
249         let handler = self.req_queue.outgoing.complete(response.id.clone());
250         handler(self, response)
251     }
252
253     pub(crate) fn send_notification<N: lsp_types::notification::Notification>(
254         &mut self,
255         params: N::Params,
256     ) {
257         let not = lsp_server::Notification::new(N::METHOD.to_string(), params);
258         self.send(not.into());
259     }
260
261     pub(crate) fn register_request(
262         &mut self,
263         request: &lsp_server::Request,
264         request_received: Instant,
265     ) {
266         self.req_queue
267             .incoming
268             .register(request.id.clone(), (request.method.clone(), request_received));
269     }
270     pub(crate) fn respond(&mut self, response: lsp_server::Response) {
271         if let Some((method, start)) = self.req_queue.incoming.complete(response.id.clone()) {
272             let duration = start.elapsed();
273             log::info!("handled req#{} in {:?}", response.id, duration);
274             let metrics = RequestMetrics { id: response.id.clone(), method, duration };
275             self.latest_requests.write().record(metrics);
276             self.send(response.into());
277         }
278     }
279     pub(crate) fn cancel(&mut self, request_id: lsp_server::RequestId) {
280         if let Some(response) = self.req_queue.incoming.cancel(request_id) {
281             self.send(response.into());
282         }
283     }
284
285     fn send(&mut self, message: lsp_server::Message) {
286         self.sender.send(message).unwrap()
287     }
288 }
289
290 impl Drop for GlobalState {
291     fn drop(&mut self) {
292         self.analysis_host.request_cancellation()
293     }
294 }
295
296 impl GlobalStateSnapshot {
297     pub(crate) fn url_to_file_id(&self, url: &Url) -> Result<FileId> {
298         url_to_file_id(&self.vfs.read().0, url)
299     }
300
301     pub(crate) fn file_id_to_url(&self, id: FileId) -> Url {
302         file_id_to_url(&self.vfs.read().0, id)
303     }
304
305     pub(crate) fn file_line_index(&self, file_id: FileId) -> Cancellable<LineIndex> {
306         let endings = self.vfs.read().1[&file_id];
307         let index = self.analysis.file_line_index(file_id)?;
308         let res = LineIndex { index, endings, encoding: self.config.offset_encoding() };
309         Ok(res)
310     }
311
312     pub(crate) fn url_file_version(&self, url: &Url) -> Option<i32> {
313         let path = from_proto::vfs_path(url).ok()?;
314         Some(self.mem_docs.get(&path)?.version)
315     }
316
317     pub(crate) fn anchored_path(&self, path: &AnchoredPathBuf) -> Url {
318         let mut base = self.vfs.read().0.file_path(path.anchor);
319         base.pop();
320         let path = base.join(&path.path).unwrap();
321         let path = path.as_path().unwrap();
322         url_from_abs_path(path)
323     }
324
325     pub(crate) fn cargo_target_for_crate_root(
326         &self,
327         crate_id: CrateId,
328     ) -> Option<(&CargoWorkspace, Target)> {
329         let file_id = self.analysis.crate_root(crate_id).ok()?;
330         let path = self.vfs.read().0.file_path(file_id);
331         let path = path.as_path()?;
332         self.workspaces.iter().find_map(|ws| match ws {
333             ProjectWorkspace::Cargo { cargo, .. } => {
334                 cargo.target_by_root(path).map(|it| (cargo, it))
335             }
336             ProjectWorkspace::Json { .. } => None,
337             ProjectWorkspace::DetachedFiles { .. } => None,
338         })
339     }
340 }
341
342 pub(crate) fn file_id_to_url(vfs: &vfs::Vfs, id: FileId) -> Url {
343     let path = vfs.file_path(id);
344     let path = path.as_path().unwrap();
345     url_from_abs_path(path)
346 }
347
348 pub(crate) fn url_to_file_id(vfs: &vfs::Vfs, url: &Url) -> Result<FileId> {
349     let path = from_proto::vfs_path(url)?;
350     let res = vfs.file_id(&path).ok_or_else(|| format!("file not found: {}", path))?;
351     Ok(res)
352 }