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