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