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