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`.
11 use crossbeam_channel::{unbounded, Receiver};
13 use parking_lot::RwLock;
14 use ra_flycheck::{Flycheck, FlycheckConfig};
15 use ra_ide::{Analysis, AnalysisChange, AnalysisHost, CrateGraph, FileId, SourceRootId};
16 use ra_project_model::{CargoWorkspace, ProcMacroClient, ProjectWorkspace, Target};
17 use ra_vfs::{LineEndings, RootEntry, Vfs, VfsChange, VfsFile, VfsTask, Watch};
21 config::{Config, FilesWatcher},
22 diagnostics::{CheckFixes, DiagnosticCollection},
23 main_loop::pending_requests::{CompletedRequest, LatestRequests},
24 to_proto::url_from_abs_path,
25 vfs_glob::{Glob, RustPackageFilterBuilder},
28 use ra_db::{CrateId, ExternSourceId};
29 use ra_progress::{ProgressSource, ProgressStatus};
30 use rustc_hash::{FxHashMap, FxHashSet};
33 workspaces: &[ProjectWorkspace],
34 config: &FlycheckConfig,
35 progress_src: &ProgressSource<(), String>,
36 ) -> Option<Flycheck> {
37 // FIXME: Figure out the multi-workspace situation
38 workspaces.iter().find_map(move |w| match w {
39 ProjectWorkspace::Cargo { cargo, .. } => {
40 let cargo_project_root = cargo.workspace_root().to_path_buf();
41 Some(Flycheck::new(config.clone(), cargo_project_root, progress_src.clone()))
43 ProjectWorkspace::Json { .. } => {
44 log::warn!("Cargo check watching only supported for cargo workspaces, disabling");
50 /// `GlobalState` is the primary mutable state of the language server
52 /// The most interesting components are `vfs`, which stores a consistent
53 /// snapshot of the file systems, and `analysis_host`, which stores our
54 /// incremental salsa database.
56 pub struct GlobalState {
58 pub local_roots: Vec<PathBuf>,
59 pub workspaces: Arc<Vec<ProjectWorkspace>>,
60 pub analysis_host: AnalysisHost,
61 pub vfs: Arc<RwLock<Vfs>>,
62 pub task_receiver: Receiver<VfsTask>,
63 pub latest_requests: Arc<RwLock<LatestRequests>>,
64 pub flycheck: Option<Flycheck>,
65 pub diagnostics: DiagnosticCollection,
66 pub proc_macro_client: ProcMacroClient,
67 pub flycheck_progress_src: ProgressSource<(), String>,
68 pub flycheck_progress_receiver: Receiver<ProgressStatus<(), String>>,
71 /// An immutable snapshot of the world's state at a point in time.
72 pub struct GlobalStateSnapshot {
74 pub workspaces: Arc<Vec<ProjectWorkspace>>,
75 pub analysis: Analysis,
76 pub latest_requests: Arc<RwLock<LatestRequests>>,
77 pub check_fixes: CheckFixes,
78 vfs: Arc<RwLock<Vfs>>,
83 workspaces: Vec<ProjectWorkspace>,
84 lru_capacity: Option<usize>,
85 exclude_globs: &[Glob],
88 let mut change = AnalysisChange::new();
90 let mut extern_dirs: FxHashSet<PathBuf> = FxHashSet::default();
92 let mut local_roots = Vec::new();
94 let create_filter = |is_member| {
95 RustPackageFilterBuilder::default()
96 .set_member(is_member)
97 .exclude(exclude_globs.iter().cloned())
100 let mut roots = Vec::new();
101 for root in workspaces.iter().flat_map(ProjectWorkspace::to_roots) {
102 let path = root.path().to_owned();
103 if root.is_member() {
104 local_roots.push(path.clone());
106 roots.push(RootEntry::new(path, create_filter(root.is_member())));
107 if let Some(out_dir) = root.out_dir() {
108 extern_dirs.insert(out_dir.to_path_buf());
109 roots.push(RootEntry::new(
110 out_dir.to_path_buf(),
111 create_filter(root.is_member()),
118 let (task_sender, task_receiver) = unbounded();
119 let task_sender = Box::new(move |t| task_sender.send(t).unwrap());
120 let watch = Watch(matches!(config.files.watcher, FilesWatcher::Notify));
121 let (mut vfs, vfs_roots) = Vfs::new(roots, task_sender, watch);
123 let mut extern_source_roots = FxHashMap::default();
125 let vfs_root_path = vfs.root2path(r);
126 let is_local = local_roots.iter().any(|it| vfs_root_path.starts_with(it));
127 change.add_root(SourceRootId(r.0), is_local);
129 // FIXME: add path2root in vfs to simpily this logic
130 if extern_dirs.contains(&vfs_root_path) {
131 extern_source_roots.insert(vfs_root_path, ExternSourceId(r.0));
135 let proc_macro_client = match &config.proc_macro_srv {
136 None => ProcMacroClient::dummy(),
137 Some((path, args)) => match ProcMacroClient::extern_process(path.into(), args) {
141 "Failed to run ra_proc_macro_srv from path {}, error: {:?}",
145 ProcMacroClient::dummy()
150 // Create crate graph from all the workspaces
151 let mut crate_graph = CrateGraph::default();
152 let mut load = |path: &Path| {
153 // Some path from metadata will be non canonicalized, e.g. /foo/../bar/lib.rs
154 let path = path.canonicalize().ok()?;
155 let vfs_file = vfs.load(&path);
156 vfs_file.map(|f| FileId(f.0))
158 for ws in workspaces.iter() {
159 crate_graph.extend(ws.to_crate_graph(
160 config.cargo.target.as_deref(),
161 &extern_source_roots,
166 change.set_crate_graph(crate_graph);
168 let (flycheck_progress_receiver, flycheck_progress_src) =
169 ProgressSource::real_if(config.client_caps.work_done_progress);
170 let flycheck = config
173 .and_then(|c| create_flycheck(&workspaces, c, &flycheck_progress_src));
175 let mut analysis_host = AnalysisHost::new(lru_capacity);
176 analysis_host.apply_change(change);
180 workspaces: Arc::new(workspaces),
182 vfs: Arc::new(RwLock::new(vfs)),
184 latest_requests: Default::default(),
186 flycheck_progress_src,
187 flycheck_progress_receiver,
188 diagnostics: Default::default(),
193 pub fn update_configuration(&mut self, config: Config) {
194 self.analysis_host.update_lru_capacity(config.lru_capacity);
195 if config.check != self.config.check {
196 self.flycheck = config
199 .and_then(|it| create_flycheck(&self.workspaces, it, &self.flycheck_progress_src));
202 self.config = config;
205 /// Returns a vec of libraries
206 /// FIXME: better API here
207 pub fn process_changes(&mut self, roots_scanned: &mut u32) -> bool {
208 let changes = self.vfs.write().commit_changes();
209 if changes.is_empty() {
212 let mut change = AnalysisChange::new();
215 VfsChange::AddRoot { root, files } => {
217 for (file, path, text) in files {
218 change.add_file(SourceRootId(root.0), FileId(file.0), path, text);
221 VfsChange::AddFile { root, file, path, text } => {
222 change.add_file(SourceRootId(root.0), FileId(file.0), path, text);
224 VfsChange::RemoveFile { root, file, path } => {
225 change.remove_file(SourceRootId(root.0), FileId(file.0), path)
227 VfsChange::ChangeFile { file, text } => {
228 change.change_file(FileId(file.0), text);
232 self.analysis_host.apply_change(change);
236 pub fn snapshot(&self) -> GlobalStateSnapshot {
237 GlobalStateSnapshot {
238 config: self.config.clone(),
239 workspaces: Arc::clone(&self.workspaces),
240 analysis: self.analysis_host.analysis(),
241 vfs: Arc::clone(&self.vfs),
242 latest_requests: Arc::clone(&self.latest_requests),
243 check_fixes: Arc::clone(&self.diagnostics.check_fixes),
247 pub fn maybe_collect_garbage(&mut self) {
248 self.analysis_host.maybe_collect_garbage()
251 pub fn collect_garbage(&mut self) {
252 self.analysis_host.collect_garbage()
255 pub fn complete_request(&mut self, request: CompletedRequest) {
256 self.latest_requests.write().record(request)
260 impl GlobalStateSnapshot {
261 pub fn analysis(&self) -> &Analysis {
265 pub fn url_to_file_id(&self, url: &Url) -> Result<FileId> {
266 let path = url.to_file_path().map_err(|()| format!("invalid uri: {}", url))?;
267 let file = self.vfs.read().path2file(&path).ok_or_else(|| {
268 // Show warning as this file is outside current workspace
269 // FIXME: just handle such files, and remove `LspError::UNKNOWN_FILE`.
271 code: LspError::UNKNOWN_FILE,
272 message: "Rust file outside current workspace is not supported yet.".to_string(),
278 pub fn file_id_to_url(&self, id: FileId) -> Url {
279 file_id_to_url(&self.vfs.read(), id)
282 pub fn file_line_endings(&self, id: FileId) -> LineEndings {
283 self.vfs.read().file_line_endings(VfsFile(id.0))
286 pub fn anchored_path(&self, file_id: FileId, path: &str) -> Url {
287 let mut base = self.vfs.read().file2path(VfsFile(file_id.0));
289 let path = base.join(path);
290 url_from_abs_path(&path)
293 pub(crate) fn cargo_target_for_crate_root(
296 ) -> Option<(&CargoWorkspace, Target)> {
297 let file_id = self.analysis().crate_root(crate_id).ok()?;
298 let path = self.vfs.read().file2path(VfsFile(file_id.0));
299 self.workspaces.iter().find_map(|ws| match ws {
300 ProjectWorkspace::Cargo { cargo, .. } => {
301 cargo.target_by_root(&path).map(|it| (cargo, it))
303 ProjectWorkspace::Json { .. } => None,
307 pub fn status(&self) -> String {
308 let mut buf = String::new();
309 if self.workspaces.is_empty() {
310 buf.push_str("no workspaces\n")
312 buf.push_str("workspaces:\n");
313 for w in self.workspaces.iter() {
314 format_to!(buf, "{} packages loaded\n", w.n_packages());
317 buf.push_str("\nanalysis:\n");
322 .unwrap_or_else(|_| "Analysis retrieval was cancelled".to_owned()),
327 pub fn workspace_root_for(&self, file_id: FileId) -> Option<&Path> {
328 let path = self.vfs.read().file2path(VfsFile(file_id.0));
329 self.workspaces.iter().find_map(|ws| ws.workspace_root_for(&path))
333 pub(crate) fn file_id_to_url(vfs: &Vfs, id: FileId) -> Url {
334 let path = vfs.file2path(VfsFile(id.0));
335 url_from_abs_path(&path)