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, Cancelable, Change, FileId};
11 use ide_db::base_db::{CrateId, VfsPath};
12 use lsp_types::{SemanticTokens, Url};
13 use parking_lot::{Mutex, RwLock};
15 BuildDataCollector, BuildDataResult, CargoWorkspace, ProcMacroClient, ProjectWorkspace, Target,
17 use rustc_hash::FxHashMap;
18 use vfs::AnchoredPathBuf;
22 diagnostics::{CheckFixes, DiagnosticCollection},
23 document::DocumentData,
25 line_index::{LineEndings, LineIndex},
28 reload::SourceRootConfig,
29 request_metrics::{LatestRequests, RequestMetrics},
30 thread_pool::TaskPool,
31 to_proto::url_from_abs_path,
35 #[derive(Eq, PartialEq, Copy, Clone)]
36 pub(crate) enum Status {
38 Ready { partial: bool },
43 impl Default for Status {
44 fn default() -> Self {
49 // Enforces drop order
50 pub(crate) struct Handle<H, C> {
52 pub(crate) receiver: C,
55 pub(crate) type ReqHandler = fn(&mut GlobalState, lsp_server::Response);
56 pub(crate) type ReqQueue = lsp_server::ReqQueue<(String, Instant), ReqHandler>;
58 /// `GlobalState` is the primary mutable state of the language server
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.
64 /// Note that this struct has more than on impl in various modules!
65 pub(crate) struct GlobalState {
66 sender: Sender<lsp_server::Message>,
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) vfs_config_version: u32,
71 pub(crate) flycheck: Vec<FlycheckHandle>,
72 pub(crate) flycheck_sender: Sender<flycheck::Message>,
73 pub(crate) flycheck_receiver: Receiver<flycheck::Message>,
74 pub(crate) config: Arc<Config>,
75 pub(crate) analysis_host: AnalysisHost,
76 pub(crate) diagnostics: DiagnosticCollection,
77 pub(crate) mem_docs: FxHashMap<VfsPath, DocumentData>,
78 pub(crate) semantic_tokens_cache: Arc<Mutex<FxHashMap<Url, SemanticTokens>>>,
79 pub(crate) vfs: Arc<RwLock<(vfs::Vfs, FxHashMap<FileId, LineEndings>)>>,
80 pub(crate) shutdown_requested: bool,
81 pub(crate) status: Status,
82 pub(crate) source_root_config: SourceRootConfig,
83 pub(crate) proc_macro_client: Option<ProcMacroClient>,
85 /// For both `workspaces` and `workspace_build_data`, the field stores the
86 /// data we actually use, while the `OpQueue` stores the result of the last
89 /// If the fetch (partially) fails, we do not update the values.
90 pub(crate) workspaces: Arc<Vec<ProjectWorkspace>>,
91 pub(crate) fetch_workspaces_queue: OpQueue<(), Vec<anyhow::Result<ProjectWorkspace>>>,
92 pub(crate) workspace_build_data: Option<BuildDataResult>,
93 pub(crate) fetch_build_data_queue:
94 OpQueue<BuildDataCollector, Option<anyhow::Result<BuildDataResult>>>,
96 latest_requests: Arc<RwLock<LatestRequests>>,
99 /// An immutable snapshot of the world's state at a point in time.
100 pub(crate) struct GlobalStateSnapshot {
101 pub(crate) config: Arc<Config>,
102 pub(crate) analysis: Analysis,
103 pub(crate) check_fixes: CheckFixes,
104 pub(crate) latest_requests: Arc<RwLock<LatestRequests>>,
105 mem_docs: FxHashMap<VfsPath, DocumentData>,
106 pub(crate) semantic_tokens_cache: Arc<Mutex<FxHashMap<Url, SemanticTokens>>>,
107 vfs: Arc<RwLock<(vfs::Vfs, FxHashMap<FileId, LineEndings>)>>,
108 pub(crate) workspaces: Arc<Vec<ProjectWorkspace>>,
112 pub(crate) fn new(sender: Sender<lsp_server::Message>, config: Config) -> GlobalState {
114 let (sender, receiver) = unbounded::<vfs::loader::Message>();
115 let handle: vfs_notify::NotifyHandle =
116 vfs::loader::Handle::spawn(Box::new(move |msg| sender.send(msg).unwrap()));
117 let handle = Box::new(handle) as Box<dyn vfs::loader::Handle>;
118 Handle { handle, receiver }
122 let (sender, receiver) = unbounded();
123 let handle = TaskPool::new(sender);
124 Handle { handle, receiver }
127 let analysis_host = AnalysisHost::new(config.lru_capacity());
128 let (flycheck_sender, flycheck_receiver) = unbounded();
131 req_queue: ReqQueue::default(),
132 vfs_config_version: 0,
135 flycheck: Vec::new(),
138 config: Arc::new(config),
140 diagnostics: Default::default(),
141 mem_docs: FxHashMap::default(),
142 semantic_tokens_cache: Arc::new(Default::default()),
143 vfs: Arc::new(RwLock::new((vfs::Vfs::default(), FxHashMap::default()))),
144 shutdown_requested: false,
145 status: Status::default(),
146 source_root_config: SourceRootConfig::default(),
147 proc_macro_client: None,
149 workspaces: Arc::new(Vec::new()),
150 fetch_workspaces_queue: OpQueue::default(),
151 workspace_build_data: None,
152 fetch_build_data_queue: OpQueue::default(),
154 latest_requests: Default::default(),
158 pub(crate) fn process_changes(&mut self) -> bool {
159 let _p = profile::span("GlobalState::process_changes");
160 let mut fs_changes = Vec::new();
161 let mut has_fs_changes = false;
164 let mut change = Change::new();
165 let (vfs, line_endings_map) = &mut *self.vfs.write();
166 let changed_files = vfs.take_changes();
167 if changed_files.is_empty() {
171 for file in changed_files {
172 if file.is_created_or_deleted() {
173 if let Some(path) = vfs.file_path(file.file_id).as_path() {
174 fs_changes.push((path.to_path_buf(), file.change_kind));
175 has_fs_changes = true;
179 let text = if file.exists() {
180 let bytes = vfs.file_contents(file.file_id).to_vec();
181 match String::from_utf8(bytes).ok() {
183 let (text, line_endings) = LineEndings::normalize(text);
184 line_endings_map.insert(file.file_id, line_endings);
192 change.change_file(file.file_id, text);
195 let roots = self.source_root_config.partition(&vfs);
196 change.set_roots(roots);
201 self.analysis_host.apply_change(change);
202 self.maybe_refresh(&fs_changes);
206 pub(crate) fn snapshot(&self) -> GlobalStateSnapshot {
207 GlobalStateSnapshot {
208 config: Arc::clone(&self.config),
209 workspaces: Arc::clone(&self.workspaces),
210 analysis: self.analysis_host.analysis(),
211 vfs: Arc::clone(&self.vfs),
212 latest_requests: Arc::clone(&self.latest_requests),
213 check_fixes: Arc::clone(&self.diagnostics.check_fixes),
214 mem_docs: self.mem_docs.clone(),
215 semantic_tokens_cache: Arc::clone(&self.semantic_tokens_cache),
219 pub(crate) fn send_request<R: lsp_types::request::Request>(
224 let request = self.req_queue.outgoing.register(R::METHOD.to_string(), params, handler);
225 self.send(request.into());
227 pub(crate) fn complete_request(&mut self, response: lsp_server::Response) {
228 let handler = self.req_queue.outgoing.complete(response.id.clone());
229 handler(self, response)
232 pub(crate) fn send_notification<N: lsp_types::notification::Notification>(
236 let not = lsp_server::Notification::new(N::METHOD.to_string(), params);
237 self.send(not.into());
240 pub(crate) fn register_request(
242 request: &lsp_server::Request,
243 request_received: Instant,
247 .register(request.id.clone(), (request.method.clone(), request_received));
249 pub(crate) fn respond(&mut self, response: lsp_server::Response) {
250 if let Some((method, start)) = self.req_queue.incoming.complete(response.id.clone()) {
251 let duration = start.elapsed();
252 log::info!("handled req#{} in {:?}", response.id, duration);
253 let metrics = RequestMetrics { id: response.id.clone(), method, duration };
254 self.latest_requests.write().record(metrics);
255 self.send(response.into());
258 pub(crate) fn cancel(&mut self, request_id: lsp_server::RequestId) {
259 if let Some(response) = self.req_queue.incoming.cancel(request_id) {
260 self.send(response.into());
264 fn send(&mut self, message: lsp_server::Message) {
265 self.sender.send(message).unwrap()
269 impl Drop for GlobalState {
271 self.analysis_host.request_cancellation()
275 impl GlobalStateSnapshot {
276 pub(crate) fn url_to_file_id(&self, url: &Url) -> Result<FileId> {
277 url_to_file_id(&self.vfs.read().0, url)
280 pub(crate) fn file_id_to_url(&self, id: FileId) -> Url {
281 file_id_to_url(&self.vfs.read().0, id)
284 pub(crate) fn file_line_index(&self, file_id: FileId) -> Cancelable<LineIndex> {
285 let endings = self.vfs.read().1[&file_id];
286 let index = self.analysis.file_line_index(file_id)?;
287 let res = LineIndex { index, endings, encoding: self.config.offset_encoding() };
291 pub(crate) fn url_file_version(&self, url: &Url) -> Option<i32> {
292 let path = from_proto::vfs_path(&url).ok()?;
293 Some(self.mem_docs.get(&path)?.version)
296 pub(crate) fn anchored_path(&self, path: &AnchoredPathBuf) -> Url {
297 let mut base = self.vfs.read().0.file_path(path.anchor);
299 let path = base.join(&path.path).unwrap();
300 let path = path.as_path().unwrap();
301 url_from_abs_path(&path)
304 pub(crate) fn cargo_target_for_crate_root(
307 ) -> Option<(&CargoWorkspace, Target)> {
308 let file_id = self.analysis.crate_root(crate_id).ok()?;
309 let path = self.vfs.read().0.file_path(file_id);
310 let path = path.as_path()?;
311 self.workspaces.iter().find_map(|ws| match ws {
312 ProjectWorkspace::Cargo { cargo, .. } => {
313 cargo.target_by_root(&path).map(|it| (cargo, it))
315 ProjectWorkspace::Json { .. } => None,
320 pub(crate) fn file_id_to_url(vfs: &vfs::Vfs, id: FileId) -> Url {
321 let path = vfs.file_path(id);
322 let path = path.as_path().unwrap();
323 url_from_abs_path(&path)
326 pub(crate) fn url_to_file_id(vfs: &vfs::Vfs, url: &Url) -> Result<FileId> {
327 let path = from_proto::vfs_path(url)?;
328 let res = vfs.file_id(&path).ok_or_else(|| format!("file not found: {}", path))?;