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};
16 Analysis, AnalysisChange, AnalysisHost, CrateGraph, FileId, LibraryData, SourceRootId,
18 use ra_project_model::{get_rustc_cfg_options, ProcMacroClient, ProjectWorkspace};
19 use ra_vfs::{LineEndings, RootEntry, Vfs, VfsChange, VfsFile, VfsRoot, VfsTask, Watch};
20 use relative_path::RelativePathBuf;
26 to_proto::url_from_path_with_drive_lowercasing, CheckFixes, DiagnosticCollection,
28 main_loop::pending_requests::{CompletedRequest, LatestRequests},
29 vfs_glob::{Glob, RustPackageFilterBuilder},
32 use ra_db::ExternSourceId;
33 use rustc_hash::{FxHashMap, FxHashSet};
35 fn create_flycheck(workspaces: &[ProjectWorkspace], config: &FlycheckConfig) -> Option<Flycheck> {
36 // FIXME: Figure out the multi-workspace situation
39 .find_map(|w| match w {
40 ProjectWorkspace::Cargo { cargo, .. } => Some(cargo),
41 ProjectWorkspace::Json { .. } => None,
44 let cargo_project_root = cargo.workspace_root().to_path_buf();
45 Some(Flycheck::new(config.clone(), cargo_project_root))
48 log::warn!("Cargo check watching only supported for cargo workspaces, disabling");
53 /// `GlobalState` is the primary mutable state of the language server
55 /// The most interesting components are `vfs`, which stores a consistent
56 /// snapshot of the file systems, and `analysis_host`, which stores our
57 /// incremental salsa database.
59 pub struct GlobalState {
61 pub local_roots: Vec<PathBuf>,
62 pub workspaces: Arc<Vec<ProjectWorkspace>>,
63 pub analysis_host: AnalysisHost,
64 pub vfs: Arc<RwLock<Vfs>>,
65 pub task_receiver: Receiver<VfsTask>,
66 pub latest_requests: Arc<RwLock<LatestRequests>>,
67 pub flycheck: Option<Flycheck>,
68 pub diagnostics: DiagnosticCollection,
69 pub proc_macro_client: ProcMacroClient,
72 /// An immutable snapshot of the world's state at a point in time.
73 pub struct GlobalStateSnapshot {
75 pub workspaces: Arc<Vec<ProjectWorkspace>>,
76 pub analysis: Analysis,
77 pub latest_requests: Arc<RwLock<LatestRequests>>,
78 pub check_fixes: CheckFixes,
79 vfs: Arc<RwLock<Vfs>>,
84 workspaces: Vec<ProjectWorkspace>,
85 lru_capacity: Option<usize>,
86 exclude_globs: &[Glob],
90 let mut change = AnalysisChange::new();
92 let extern_dirs: FxHashSet<_> =
93 workspaces.iter().flat_map(ProjectWorkspace::out_dirs).collect();
95 let mut local_roots = Vec::new();
97 let create_filter = |is_member| {
98 RustPackageFilterBuilder::default()
99 .set_member(is_member)
100 .exclude(exclude_globs.iter().cloned())
105 .flat_map(ProjectWorkspace::to_roots)
107 let path = pkg_root.path().to_owned();
108 if pkg_root.is_member() {
109 local_roots.push(path.clone());
111 RootEntry::new(path, create_filter(pkg_root.is_member()))
116 .map(|path| RootEntry::new(path.to_owned(), create_filter(false))),
121 let (task_sender, task_receiver) = unbounded();
122 let task_sender = Box::new(move |t| task_sender.send(t).unwrap());
123 let (mut vfs, vfs_roots) = Vfs::new(roots, task_sender, watch);
125 let mut extern_source_roots = FxHashMap::default();
127 let vfs_root_path = vfs.root2path(r);
128 let is_local = local_roots.iter().any(|it| vfs_root_path.starts_with(it));
129 change.add_root(SourceRootId(r.0), is_local);
130 change.set_debug_root_path(SourceRootId(r.0), vfs_root_path.display().to_string());
132 // FIXME: add path2root in vfs to simpily this logic
133 if extern_dirs.contains(&vfs_root_path) {
134 extern_source_roots.insert(vfs_root_path, ExternSourceId(r.0));
138 // FIXME: Read default cfgs from config
139 let default_cfg_options = {
140 let mut opts = get_rustc_cfg_options(config.cargo.target.as_ref());
141 opts.insert_atom("test".into());
142 opts.insert_atom("debug_assertion".into());
146 let proc_macro_client = match &config.proc_macro_srv {
147 None => ProcMacroClient::dummy(),
148 Some((path, args)) => match ProcMacroClient::extern_process(path.into(), args) {
152 "Failed to run ra_proc_macro_srv from path {}, error: {:?}",
156 ProcMacroClient::dummy()
161 // Create crate graph from all the workspaces
162 let mut crate_graph = CrateGraph::default();
163 let mut load = |path: &Path| {
164 // Some path from metadata will be non canonicalized, e.g. /foo/../bar/lib.rs
165 let path = path.canonicalize().ok()?;
166 let vfs_file = vfs.load(&path);
167 vfs_file.map(|f| FileId(f.0))
169 for ws in workspaces.iter() {
170 crate_graph.extend(ws.to_crate_graph(
171 &default_cfg_options,
172 &extern_source_roots,
177 change.set_crate_graph(crate_graph);
179 let flycheck = config.check.as_ref().and_then(|c| create_flycheck(&workspaces, c));
181 let mut analysis_host = AnalysisHost::new(lru_capacity);
182 analysis_host.apply_change(change);
186 workspaces: Arc::new(workspaces),
188 vfs: Arc::new(RwLock::new(vfs)),
190 latest_requests: Default::default(),
192 diagnostics: Default::default(),
197 pub fn update_configuration(&mut self, config: Config) {
198 self.analysis_host.update_lru_capacity(config.lru_capacity);
199 if config.check != self.config.check {
201 config.check.as_ref().and_then(|it| create_flycheck(&self.workspaces, it));
204 self.config = config;
207 /// Returns a vec of libraries
208 /// FIXME: better API here
209 pub fn process_changes(
211 roots_scanned: &mut usize,
212 ) -> Option<Vec<(SourceRootId, Vec<(FileId, RelativePathBuf, Arc<String>)>)>> {
213 let changes = self.vfs.write().commit_changes();
214 if changes.is_empty() {
217 let mut libs = Vec::new();
218 let mut change = AnalysisChange::new();
221 VfsChange::AddRoot { root, files } => {
222 let root_path = self.vfs.read().root2path(root);
223 let is_local = self.local_roots.iter().any(|r| root_path.starts_with(r));
226 for (file, path, text) in files {
227 change.add_file(SourceRootId(root.0), FileId(file.0), path, text);
232 .map(|(vfsfile, path, text)| (FileId(vfsfile.0), path, text))
234 libs.push((SourceRootId(root.0), files));
237 VfsChange::AddFile { root, file, path, text } => {
238 change.add_file(SourceRootId(root.0), FileId(file.0), path, text);
240 VfsChange::RemoveFile { root, file, path } => {
241 change.remove_file(SourceRootId(root.0), FileId(file.0), path)
243 VfsChange::ChangeFile { file, text } => {
244 change.change_file(FileId(file.0), text);
248 self.analysis_host.apply_change(change);
252 pub fn add_lib(&mut self, data: LibraryData) {
253 let mut change = AnalysisChange::new();
254 change.add_library(data);
255 self.analysis_host.apply_change(change);
258 pub fn snapshot(&self) -> GlobalStateSnapshot {
259 GlobalStateSnapshot {
260 config: self.config.clone(),
261 workspaces: Arc::clone(&self.workspaces),
262 analysis: self.analysis_host.analysis(),
263 vfs: Arc::clone(&self.vfs),
264 latest_requests: Arc::clone(&self.latest_requests),
265 check_fixes: Arc::clone(&self.diagnostics.check_fixes),
269 pub fn maybe_collect_garbage(&mut self) {
270 self.analysis_host.maybe_collect_garbage()
273 pub fn collect_garbage(&mut self) {
274 self.analysis_host.collect_garbage()
277 pub fn complete_request(&mut self, request: CompletedRequest) {
278 self.latest_requests.write().record(request)
282 impl GlobalStateSnapshot {
283 pub fn analysis(&self) -> &Analysis {
287 pub fn uri_to_file_id(&self, uri: &Url) -> Result<FileId> {
288 let path = uri.to_file_path().map_err(|()| format!("invalid uri: {}", uri))?;
289 let file = self.vfs.read().path2file(&path).ok_or_else(|| {
290 // Show warning as this file is outside current workspace
291 // FIXME: just handle such files, and remove `LspError::UNKNOWN_FILE`.
293 code: LspError::UNKNOWN_FILE,
294 message: "Rust file outside current workspace is not supported yet.".to_string(),
300 pub fn file_id_to_uri(&self, id: FileId) -> Result<Url> {
301 let path = self.vfs.read().file2path(VfsFile(id.0));
302 let url = url_from_path_with_drive_lowercasing(path)?;
307 pub fn file_id_to_path(&self, id: FileId) -> PathBuf {
308 self.vfs.read().file2path(VfsFile(id.0))
311 pub fn file_line_endings(&self, id: FileId) -> LineEndings {
312 self.vfs.read().file_line_endings(VfsFile(id.0))
315 pub fn path_to_uri(&self, root: SourceRootId, path: &RelativePathBuf) -> Result<Url> {
316 let base = self.vfs.read().root2path(VfsRoot(root.0));
317 let path = path.to_path(base);
318 let url = Url::from_file_path(&path)
319 .map_err(|_| format!("can't convert path to url: {}", path.display()))?;
323 pub fn status(&self) -> String {
324 let mut buf = String::new();
325 if self.workspaces.is_empty() {
326 buf.push_str("no workspaces\n")
328 buf.push_str("workspaces:\n");
329 for w in self.workspaces.iter() {
330 format_to!(buf, "{} packages loaded\n", w.n_packages());
333 buf.push_str("\nanalysis:\n");
338 .unwrap_or_else(|_| "Analysis retrieval was cancelled".to_owned()),
343 pub fn workspace_root_for(&self, file_id: FileId) -> Option<&Path> {
344 let path = self.vfs.read().file2path(VfsFile(file_id.0));
345 self.workspaces.iter().find_map(|ws| ws.workspace_root_for(&path))