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;
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;
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,
31 #[derive(Eq, PartialEq, Copy, Clone)]
32 pub(crate) enum Status {
39 impl Default for Status {
40 fn default() -> Self {
45 // Enforces drop order
46 pub(crate) struct Handle<H, C> {
48 pub(crate) receiver: C,
51 pub(crate) type ReqHandler = fn(&mut GlobalState, lsp_server::Response);
52 pub(crate) type ReqQueue = lsp_server::ReqQueue<(String, Instant), ReqHandler>;
54 /// `GlobalState` is the primary mutable state of the language server
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.
60 /// Note that this struct has more than on impl in various modules!
61 pub(crate) struct GlobalState {
62 sender: Sender<lsp_server::Message>,
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) mem_docs: FxHashMap<VfsPath, DocumentData>,
73 pub(crate) semantic_tokens_cache: Arc<Mutex<FxHashMap<Url, SemanticTokens>>>,
74 pub(crate) vfs: Arc<RwLock<(vfs::Vfs, FxHashMap<FileId, LineEndings>)>>,
75 pub(crate) shutdown_requested: bool,
76 pub(crate) status: Status,
77 pub(crate) source_root_config: SourceRootConfig,
78 pub(crate) proc_macro_client: ProcMacroClient,
79 pub(crate) workspaces: Arc<Vec<ProjectWorkspace>>,
80 latest_requests: Arc<RwLock<LatestRequests>>,
83 /// An immutable snapshot of the world's state at a point in time.
84 pub(crate) struct GlobalStateSnapshot {
85 pub(crate) config: Config,
86 pub(crate) analysis: Analysis,
87 pub(crate) check_fixes: CheckFixes,
88 pub(crate) latest_requests: Arc<RwLock<LatestRequests>>,
89 mem_docs: FxHashMap<VfsPath, DocumentData>,
90 pub(crate) semantic_tokens_cache: Arc<Mutex<FxHashMap<Url, SemanticTokens>>>,
91 vfs: Arc<RwLock<(vfs::Vfs, FxHashMap<FileId, LineEndings>)>>,
92 pub(crate) workspaces: Arc<Vec<ProjectWorkspace>>,
96 pub(crate) fn new(sender: Sender<lsp_server::Message>, config: Config) -> GlobalState {
98 let (sender, receiver) = unbounded::<vfs::loader::Message>();
99 let handle: vfs_notify::NotifyHandle =
100 vfs::loader::Handle::spawn(Box::new(move |msg| sender.send(msg).unwrap()));
101 let handle = Box::new(handle) as Box<dyn vfs::loader::Handle>;
102 Handle { handle, receiver }
106 let (sender, receiver) = unbounded();
107 let handle = TaskPool::new(sender);
108 Handle { handle, receiver }
111 let analysis_host = AnalysisHost::new(config.lru_capacity);
112 let (flycheck_sender, flycheck_receiver) = unbounded();
115 req_queue: ReqQueue::default(),
118 flycheck: Vec::new(),
123 diagnostics: Default::default(),
124 mem_docs: FxHashMap::default(),
125 semantic_tokens_cache: Arc::new(Default::default()),
126 vfs: Arc::new(RwLock::new((vfs::Vfs::default(), FxHashMap::default()))),
127 shutdown_requested: false,
128 status: Status::default(),
129 source_root_config: SourceRootConfig::default(),
130 proc_macro_client: ProcMacroClient::dummy(),
131 workspaces: Arc::new(Vec::new()),
132 latest_requests: Default::default(),
136 pub(crate) fn process_changes(&mut self) -> bool {
137 let _p = profile::span("GlobalState::process_changes");
138 let mut fs_changes = Vec::new();
139 let mut has_fs_changes = false;
142 let mut change = Change::new();
143 let (vfs, line_endings_map) = &mut *self.vfs.write();
144 let changed_files = vfs.take_changes();
145 if changed_files.is_empty() {
149 for file in changed_files {
150 if file.is_created_or_deleted() {
151 if let Some(path) = vfs.file_path(file.file_id).as_path() {
152 fs_changes.push((path.to_path_buf(), file.change_kind));
153 has_fs_changes = true;
157 let text = if file.exists() {
158 let bytes = vfs.file_contents(file.file_id).to_vec();
159 match String::from_utf8(bytes).ok() {
161 let (text, line_endings) = LineEndings::normalize(text);
162 line_endings_map.insert(file.file_id, line_endings);
170 change.change_file(file.file_id, text);
173 let roots = self.source_root_config.partition(&vfs);
174 change.set_roots(roots);
179 self.analysis_host.apply_change(change);
180 self.maybe_refresh(&fs_changes);
184 pub(crate) fn snapshot(&self) -> GlobalStateSnapshot {
185 GlobalStateSnapshot {
186 config: self.config.clone(),
187 workspaces: Arc::clone(&self.workspaces),
188 analysis: self.analysis_host.analysis(),
189 vfs: Arc::clone(&self.vfs),
190 latest_requests: Arc::clone(&self.latest_requests),
191 check_fixes: Arc::clone(&self.diagnostics.check_fixes),
192 mem_docs: self.mem_docs.clone(),
193 semantic_tokens_cache: Arc::clone(&self.semantic_tokens_cache),
197 pub(crate) fn send_request<R: lsp_types::request::Request>(
202 let request = self.req_queue.outgoing.register(R::METHOD.to_string(), params, handler);
203 self.send(request.into());
205 pub(crate) fn complete_request(&mut self, response: lsp_server::Response) {
206 let handler = self.req_queue.outgoing.complete(response.id.clone());
207 handler(self, response)
210 pub(crate) fn send_notification<N: lsp_types::notification::Notification>(
214 let not = lsp_server::Notification::new(N::METHOD.to_string(), params);
215 self.send(not.into());
218 pub(crate) fn register_request(
220 request: &lsp_server::Request,
221 request_received: Instant,
225 .register(request.id.clone(), (request.method.clone(), request_received));
227 pub(crate) fn respond(&mut self, response: lsp_server::Response) {
228 if let Some((method, start)) = self.req_queue.incoming.complete(response.id.clone()) {
229 let duration = start.elapsed();
230 log::info!("handled req#{} in {:?}", response.id, duration);
231 let metrics = RequestMetrics { id: response.id.clone(), method, duration };
232 self.latest_requests.write().record(metrics);
233 self.send(response.into());
236 pub(crate) fn cancel(&mut self, request_id: lsp_server::RequestId) {
237 if let Some(response) = self.req_queue.incoming.cancel(request_id) {
238 self.send(response.into());
242 fn send(&mut self, message: lsp_server::Message) {
243 self.sender.send(message).unwrap()
247 impl Drop for GlobalState {
249 self.analysis_host.request_cancellation()
253 impl GlobalStateSnapshot {
254 pub(crate) fn url_to_file_id(&self, url: &Url) -> Result<FileId> {
255 url_to_file_id(&self.vfs.read().0, url)
258 pub(crate) fn file_id_to_url(&self, id: FileId) -> Url {
259 file_id_to_url(&self.vfs.read().0, id)
262 pub(crate) fn file_line_endings(&self, id: FileId) -> LineEndings {
263 self.vfs.read().1[&id]
266 pub(crate) fn url_file_version(&self, url: &Url) -> Option<i64> {
267 let path = from_proto::vfs_path(&url).ok()?;
268 self.mem_docs.get(&path)?.version
271 pub(crate) fn anchored_path(&self, file_id: FileId, path: &str) -> Url {
272 let mut base = self.vfs.read().0.file_path(file_id);
274 let path = base.join(path).unwrap();
275 let path = path.as_path().unwrap();
276 url_from_abs_path(&path)
279 pub(crate) fn cargo_target_for_crate_root(
282 ) -> Option<(&CargoWorkspace, Target)> {
283 let file_id = self.analysis.crate_root(crate_id).ok()?;
284 let path = self.vfs.read().0.file_path(file_id);
285 let path = path.as_path()?;
286 self.workspaces.iter().find_map(|ws| match ws {
287 ProjectWorkspace::Cargo { cargo, .. } => {
288 cargo.target_by_root(&path).map(|it| (cargo, it))
290 ProjectWorkspace::Json { .. } => None,
295 pub(crate) fn file_id_to_url(vfs: &vfs::Vfs, id: FileId) -> Url {
296 let path = vfs.file_path(id);
297 let path = path.as_path().unwrap();
298 url_from_abs_path(&path)
301 pub(crate) fn url_to_file_id(vfs: &vfs::Vfs, url: &Url) -> Result<FileId> {
302 let path = from_proto::vfs_path(url)?;
303 let res = vfs.file_id(&path).ok_or_else(|| format!("file not found: {}", path))?;