1 //! The context or environment in which the language server functions. In our
2 //! server implementation this is know as the `WorldState`.
4 //! Each tick provides an immutable snapshot of the state as `WorldSnapshot`.
6 use std::{sync::Arc, time::Instant};
8 use crossbeam_channel::{unbounded, Receiver, Sender};
9 use flycheck::FlycheckHandle;
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;
19 diagnostics::{CheckFixes, DiagnosticCollection},
20 document::DocumentData,
22 line_endings::LineEndings,
24 reload::SourceRootConfig,
25 request_metrics::{LatestRequests, RequestMetrics},
26 thread_pool::TaskPool,
27 to_proto::url_from_abs_path,
32 #[derive(Eq, PartialEq, Copy, Clone)]
33 pub(crate) enum Status {
40 impl Default for Status {
41 fn default() -> Self {
46 // Enforces drop order
47 pub(crate) struct Handle<H, C> {
49 pub(crate) receiver: C,
52 pub(crate) type ReqHandler = fn(&mut GlobalState, lsp_server::Response);
53 pub(crate) type ReqQueue = lsp_server::ReqQueue<(String, Instant), ReqHandler>;
55 /// `GlobalState` is the primary mutable state of the language server
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.
61 /// Note that this struct has more than on impl in various modules!
62 pub(crate) struct GlobalState {
63 sender: Sender<lsp_server::Message>,
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>>,
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>>,
94 pub(crate) fn new(sender: Sender<lsp_server::Message>, config: Config) -> GlobalState {
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 }
104 let (sender, receiver) = unbounded();
105 let handle = TaskPool::new(sender);
106 Handle { handle, receiver }
109 let analysis_host = AnalysisHost::new(config.lru_capacity);
110 let (flycheck_sender, flycheck_receiver) = unbounded();
113 req_queue: ReqQueue::default(),
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(),
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;
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() {
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;
153 let text = if file.exists() {
154 let bytes = vfs.file_contents(file.file_id).to_vec();
155 match String::from_utf8(bytes).ok() {
157 let (text, line_endings) = LineEndings::normalize(text);
158 line_endings_map.insert(file.file_id, line_endings);
166 change.change_file(file.file_id, text);
169 let roots = self.source_root_config.partition(&vfs);
170 change.set_roots(roots);
175 self.analysis_host.apply_change(change);
176 self.maybe_refresh(&fs_changes);
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(),
192 pub(crate) fn send_request<R: lsp_types::request::Request>(
197 let request = self.req_queue.outgoing.register(R::METHOD.to_string(), params, handler);
198 self.send(request.into());
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)
205 pub(crate) fn send_notification<N: lsp_types::notification::Notification>(
209 let not = lsp_server::Notification::new(N::METHOD.to_string(), params);
210 self.send(not.into());
213 pub(crate) fn register_request(
215 request: &lsp_server::Request,
216 request_received: Instant,
220 .register(request.id.clone(), (request.method.clone(), request_received));
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());
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());
237 fn send(&mut self, message: lsp_server::Message) {
238 self.sender.send(message).unwrap()
242 impl Drop for GlobalState {
244 self.analysis_host.request_cancellation()
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)
253 pub(crate) fn file_id_to_url(&self, id: FileId) -> Url {
254 file_id_to_url(&self.vfs.read().0, id)
257 pub(crate) fn file_line_endings(&self, id: FileId) -> LineEndings {
258 self.vfs.read().1[&id]
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
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);
269 let path = base.join(path).unwrap();
270 let path = path.as_path().unwrap();
271 url_from_abs_path(&path)
274 pub(crate) fn cargo_target_for_crate_root(
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))
285 ProjectWorkspace::Json { .. } => None,
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)
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))?;