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