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};
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 rustc_hash::{FxHashMap, FxHashSet};
31 fn create_flycheck(workspaces: &[ProjectWorkspace], config: &FlycheckConfig) -> Option<Flycheck> {
32 // FIXME: Figure out the multi-workspace situation
33 workspaces.iter().find_map(|w| match w {
34 ProjectWorkspace::Cargo { cargo, .. } => {
35 let cargo_project_root = cargo.workspace_root().to_path_buf();
36 Some(Flycheck::new(config.clone(), cargo_project_root))
38 ProjectWorkspace::Json { .. } => {
39 log::warn!("Cargo check watching only supported for cargo workspaces, disabling");
45 /// `GlobalState` is the primary mutable state of the language server
47 /// The most interesting components are `vfs`, which stores a consistent
48 /// snapshot of the file systems, and `analysis_host`, which stores our
49 /// incremental salsa database.
51 pub struct GlobalState {
53 pub local_roots: Vec<PathBuf>,
54 pub workspaces: Arc<Vec<ProjectWorkspace>>,
55 pub analysis_host: AnalysisHost,
56 pub vfs: Arc<RwLock<Vfs>>,
57 pub task_receiver: Receiver<VfsTask>,
58 pub latest_requests: Arc<RwLock<LatestRequests>>,
59 pub flycheck: Option<Flycheck>,
60 pub diagnostics: DiagnosticCollection,
61 pub proc_macro_client: ProcMacroClient,
64 /// An immutable snapshot of the world's state at a point in time.
65 pub struct GlobalStateSnapshot {
67 pub workspaces: Arc<Vec<ProjectWorkspace>>,
68 pub analysis: Analysis,
69 pub latest_requests: Arc<RwLock<LatestRequests>>,
70 pub check_fixes: CheckFixes,
71 vfs: Arc<RwLock<Vfs>>,
76 workspaces: Vec<ProjectWorkspace>,
77 lru_capacity: Option<usize>,
78 exclude_globs: &[Glob],
82 let mut change = AnalysisChange::new();
84 let mut extern_dirs: FxHashSet<PathBuf> = FxHashSet::default();
86 let mut local_roots = Vec::new();
88 let create_filter = |is_member| {
89 RustPackageFilterBuilder::default()
90 .set_member(is_member)
91 .exclude(exclude_globs.iter().cloned())
94 let mut roots = Vec::new();
95 for root in workspaces.iter().flat_map(ProjectWorkspace::to_roots) {
96 let path = root.path().to_owned();
98 local_roots.push(path.clone());
100 roots.push(RootEntry::new(path, create_filter(root.is_member())));
101 if let Some(out_dir) = root.out_dir() {
102 extern_dirs.insert(out_dir.to_path_buf());
103 roots.push(RootEntry::new(
104 out_dir.to_path_buf(),
105 create_filter(root.is_member()),
112 let (task_sender, task_receiver) = unbounded();
113 let task_sender = Box::new(move |t| task_sender.send(t).unwrap());
114 let (mut vfs, vfs_roots) = Vfs::new(roots, task_sender, watch);
116 let mut extern_source_roots = FxHashMap::default();
118 let vfs_root_path = vfs.root2path(r);
119 let is_local = local_roots.iter().any(|it| vfs_root_path.starts_with(it));
120 change.add_root(SourceRootId(r.0), is_local);
122 // FIXME: add path2root in vfs to simpily this logic
123 if extern_dirs.contains(&vfs_root_path) {
124 extern_source_roots.insert(vfs_root_path, ExternSourceId(r.0));
128 let proc_macro_client = match &config.proc_macro_srv {
129 None => ProcMacroClient::dummy(),
130 Some((path, args)) => match ProcMacroClient::extern_process(path.into(), args) {
134 "Failed to run ra_proc_macro_srv from path {}, error: {:?}",
138 ProcMacroClient::dummy()
143 // Create crate graph from all the workspaces
144 let mut crate_graph = CrateGraph::default();
145 let mut load = |path: &Path| {
146 // Some path from metadata will be non canonicalized, e.g. /foo/../bar/lib.rs
147 let path = path.canonicalize().ok()?;
148 let vfs_file = vfs.load(&path);
149 vfs_file.map(|f| FileId(f.0))
151 for ws in workspaces.iter() {
152 crate_graph.extend(ws.to_crate_graph(
153 config.cargo.target.as_deref(),
154 &extern_source_roots,
159 change.set_crate_graph(crate_graph);
161 let flycheck = config.check.as_ref().and_then(|c| create_flycheck(&workspaces, c));
163 let mut analysis_host = AnalysisHost::new(lru_capacity);
164 analysis_host.apply_change(change);
168 workspaces: Arc::new(workspaces),
170 vfs: Arc::new(RwLock::new(vfs)),
172 latest_requests: Default::default(),
174 diagnostics: Default::default(),
179 pub fn update_configuration(&mut self, config: Config) {
180 self.analysis_host.update_lru_capacity(config.lru_capacity);
181 if config.check != self.config.check {
183 config.check.as_ref().and_then(|it| create_flycheck(&self.workspaces, it));
186 self.config = config;
189 /// Returns a vec of libraries
190 /// FIXME: better API here
191 pub fn process_changes(&mut self, roots_scanned: &mut usize) -> bool {
192 let changes = self.vfs.write().commit_changes();
193 if changes.is_empty() {
196 let mut change = AnalysisChange::new();
199 VfsChange::AddRoot { root, files } => {
201 for (file, path, text) in files {
202 change.add_file(SourceRootId(root.0), FileId(file.0), path, text);
205 VfsChange::AddFile { root, file, path, text } => {
206 change.add_file(SourceRootId(root.0), FileId(file.0), path, text);
208 VfsChange::RemoveFile { root, file, path } => {
209 change.remove_file(SourceRootId(root.0), FileId(file.0), path)
211 VfsChange::ChangeFile { file, text } => {
212 change.change_file(FileId(file.0), text);
216 self.analysis_host.apply_change(change);
220 pub fn snapshot(&self) -> GlobalStateSnapshot {
221 GlobalStateSnapshot {
222 config: self.config.clone(),
223 workspaces: Arc::clone(&self.workspaces),
224 analysis: self.analysis_host.analysis(),
225 vfs: Arc::clone(&self.vfs),
226 latest_requests: Arc::clone(&self.latest_requests),
227 check_fixes: Arc::clone(&self.diagnostics.check_fixes),
231 pub fn maybe_collect_garbage(&mut self) {
232 self.analysis_host.maybe_collect_garbage()
235 pub fn collect_garbage(&mut self) {
236 self.analysis_host.collect_garbage()
239 pub fn complete_request(&mut self, request: CompletedRequest) {
240 self.latest_requests.write().record(request)
244 impl GlobalStateSnapshot {
245 pub fn analysis(&self) -> &Analysis {
249 pub fn url_to_file_id(&self, url: &Url) -> Result<FileId> {
250 let path = url.to_file_path().map_err(|()| format!("invalid uri: {}", url))?;
251 let file = self.vfs.read().path2file(&path).ok_or_else(|| {
252 // Show warning as this file is outside current workspace
253 // FIXME: just handle such files, and remove `LspError::UNKNOWN_FILE`.
255 code: LspError::UNKNOWN_FILE,
256 message: "Rust file outside current workspace is not supported yet.".to_string(),
262 pub fn file_id_to_url(&self, id: FileId) -> Url {
263 file_id_to_url(&self.vfs.read(), id)
266 pub fn file_line_endings(&self, id: FileId) -> LineEndings {
267 self.vfs.read().file_line_endings(VfsFile(id.0))
270 pub fn anchored_path(&self, file_id: FileId, path: &str) -> Url {
271 let mut base = self.vfs.read().file2path(VfsFile(file_id.0));
273 let path = base.join(path);
274 url_from_abs_path(&path)
277 pub(crate) fn cargo_target_for_crate_root(
280 ) -> Option<(&CargoWorkspace, Target)> {
281 let file_id = self.analysis().crate_root(crate_id).ok()?;
282 let path = self.vfs.read().file2path(VfsFile(file_id.0));
283 self.workspaces.iter().find_map(|ws| match ws {
284 ProjectWorkspace::Cargo { cargo, .. } => {
285 cargo.target_by_root(&path).map(|it| (cargo, it))
287 ProjectWorkspace::Json { .. } => None,
291 pub fn status(&self) -> String {
292 let mut buf = String::new();
293 if self.workspaces.is_empty() {
294 buf.push_str("no workspaces\n")
296 buf.push_str("workspaces:\n");
297 for w in self.workspaces.iter() {
298 format_to!(buf, "{} packages loaded\n", w.n_packages());
301 buf.push_str("\nanalysis:\n");
306 .unwrap_or_else(|_| "Analysis retrieval was cancelled".to_owned()),
311 pub fn workspace_root_for(&self, file_id: FileId) -> Option<&Path> {
312 let path = self.vfs.read().file2path(VfsFile(file_id.0));
313 self.workspaces.iter().find_map(|ws| ws.workspace_root_for(&path))
317 pub(crate) fn file_id_to_url(vfs: &Vfs, id: FileId) -> Url {
318 let path = vfs.file2path(VfsFile(id.0));
319 url_from_abs_path(&path)