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