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