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