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