Files
rust/crates/rust-analyzer/src/global_state.rs

321 lines
11 KiB
Rust
Raw Normal View History

2020-02-18 12:25:26 +01:00
//! The context or environment in which the language server functions. In our
//! server implementation this is know as the `WorldState`.
2019-12-21 15:27:38 -05:00
//!
//! Each tick provides an immutable snapshot of the state as `WorldSnapshot`.
2018-08-17 19:54:08 +03:00
use std::{
path::{Path, PathBuf},
2018-09-02 14:46:15 +03:00
sync::Arc,
2018-08-17 19:54:08 +03:00
};
2019-08-25 13:04:56 +03:00
use crossbeam_channel::{unbounded, Receiver};
2019-01-14 13:55:56 +03:00
use lsp_types::Url;
use parking_lot::RwLock;
use ra_flycheck::{Flycheck, FlycheckConfig};
use ra_ide::{Analysis, AnalysisChange, AnalysisHost, CrateGraph, FileId, SourceRootId};
use ra_project_model::{CargoWorkspace, ProcMacroClient, ProjectWorkspace, Target};
use ra_vfs::{LineEndings, RootEntry, Vfs, VfsChange, VfsFile, VfsTask, Watch};
2020-03-28 11:08:19 +01:00
use stdx::format_to;
2018-08-17 19:54:08 +03:00
2018-10-15 20:15:53 +03:00
use crate::{
2020-06-18 12:39:41 +02:00
config::{Config, FilesWatcher},
2020-06-13 11:00:06 +02:00
diagnostics::{CheckFixes, DiagnosticCollection},
2020-06-20 23:08:01 +02:00
main_loop::request_metrics::{LatestRequests, RequestMetrics},
2020-06-13 11:00:06 +02:00
to_proto::url_from_abs_path,
2020-02-17 19:07:30 +01:00
vfs_glob::{Glob, RustPackageFilterBuilder},
LspError, Result,
2018-08-17 19:54:08 +03:00
};
use ra_db::{CrateId, ExternSourceId};
2020-03-10 22:00:58 +08:00
use rustc_hash::{FxHashMap, FxHashSet};
2018-08-17 19:54:08 +03:00
2020-04-01 18:41:43 +02:00
fn create_flycheck(workspaces: &[ProjectWorkspace], config: &FlycheckConfig) -> Option<Flycheck> {
// FIXME: Figure out the multi-workspace situation
2020-06-18 02:00:48 +03:00
workspaces.iter().find_map(|w| match w {
ProjectWorkspace::Cargo { cargo, .. } => {
2020-03-21 00:40:02 +02:00
let cargo_project_root = cargo.workspace_root().to_path_buf();
2020-04-01 18:41:43 +02:00
Some(Flycheck::new(config.clone(), cargo_project_root))
2020-06-18 02:00:48 +03:00
}
ProjectWorkspace::Json { .. } => {
2020-03-21 00:40:02 +02:00
log::warn!("Cargo check watching only supported for cargo workspaces, disabling");
None
2020-06-18 02:00:48 +03:00
}
})
2020-03-21 00:40:02 +02:00
}
2020-06-03 11:16:08 +02:00
/// `GlobalState` is the primary mutable state of the language server
2019-06-01 10:31:40 +03:00
///
/// The most interesting components are `vfs`, which stores a consistent
/// snapshot of the file systems, and `analysis_host`, which stores our
/// incremental salsa database.
2018-12-19 15:04:15 +03:00
#[derive(Debug)]
2020-06-03 11:16:08 +02:00
pub struct GlobalState {
2020-03-31 16:02:55 +02:00
pub config: Config,
2020-06-03 10:52:35 +02:00
pub local_roots: Vec<PathBuf>,
2019-01-10 20:13:08 +03:00
pub workspaces: Arc<Vec<ProjectWorkspace>>,
2018-08-30 12:51:46 +03:00
pub analysis_host: AnalysisHost,
2018-12-19 15:04:15 +03:00
pub vfs: Arc<RwLock<Vfs>>,
2019-08-25 13:04:56 +03:00
pub task_receiver: Receiver<VfsTask>,
pub flycheck: Option<Flycheck>,
pub diagnostics: DiagnosticCollection,
2020-04-13 00:05:33 +08:00
pub proc_macro_client: ProcMacroClient,
2020-06-20 23:08:01 +02:00
pub(crate) latest_requests: Arc<RwLock<LatestRequests>>,
2018-08-17 19:54:08 +03:00
}
2019-06-01 10:31:40 +03:00
/// An immutable snapshot of the world's state at a point in time.
2020-06-03 11:16:08 +02:00
pub struct GlobalStateSnapshot {
2020-03-31 16:02:55 +02:00
pub config: Config,
2019-01-10 20:13:08 +03:00
pub workspaces: Arc<Vec<ProjectWorkspace>>,
2018-08-29 18:03:14 +03:00
pub analysis: Analysis,
pub check_fixes: CheckFixes,
2020-06-20 23:08:01 +02:00
pub(crate) latest_requests: Arc<RwLock<LatestRequests>>,
2020-01-16 11:58:31 +01:00
vfs: Arc<RwLock<Vfs>>,
2018-08-17 19:54:08 +03:00
}
2020-06-03 11:16:08 +02:00
impl GlobalState {
2019-06-07 20:49:29 +03:00
pub fn new(
workspaces: Vec<ProjectWorkspace>,
lru_capacity: Option<usize>,
exclude_globs: &[Glob],
2020-03-31 16:02:55 +02:00
config: Config,
2020-06-03 11:16:08 +02:00
) -> GlobalState {
let mut change = AnalysisChange::new();
2018-08-17 19:54:08 +03:00
2020-06-10 12:08:35 +02:00
let mut extern_dirs: FxHashSet<PathBuf> = FxHashSet::default();
2020-04-01 02:15:20 +03:00
2020-06-03 10:52:35 +02:00
let mut local_roots = Vec::new();
2020-04-01 02:15:20 +03:00
let roots: Vec<_> = {
let create_filter = |is_member| {
RustPackageFilterBuilder::default()
.set_member(is_member)
.exclude(exclude_globs.iter().cloned())
.into_vfs_filter()
};
2020-06-10 12:08:35 +02:00
let mut roots = Vec::new();
for root in workspaces.iter().flat_map(ProjectWorkspace::to_roots) {
let path = root.path().to_owned();
if root.is_member() {
local_roots.push(path.clone());
}
roots.push(RootEntry::new(path, create_filter(root.is_member())));
if let Some(out_dir) = root.out_dir() {
extern_dirs.insert(out_dir.to_path_buf());
roots.push(RootEntry::new(
out_dir.to_path_buf(),
create_filter(root.is_member()),
))
}
}
roots
2020-04-01 02:15:20 +03:00
};
2020-03-10 22:00:58 +08:00
2019-08-25 13:04:56 +03:00
let (task_sender, task_receiver) = unbounded();
let task_sender = Box::new(move |t| task_sender.send(t).unwrap());
2020-06-18 12:39:41 +02:00
let watch = Watch(matches!(config.files.watcher, FilesWatcher::Notify));
2019-09-06 16:25:24 +03:00
let (mut vfs, vfs_roots) = Vfs::new(roots, task_sender, watch);
2020-03-29 06:33:16 +08:00
2020-04-01 02:15:20 +03:00
let mut extern_source_roots = FxHashMap::default();
for r in vfs_roots {
let vfs_root_path = vfs.root2path(r);
2020-06-03 10:52:35 +02:00
let is_local = local_roots.iter().any(|it| vfs_root_path.starts_with(it));
2019-06-03 10:21:08 -04:00
change.add_root(SourceRootId(r.0), is_local);
2020-03-10 22:00:58 +08:00
// FIXME: add path2root in vfs to simpily this logic
if extern_dirs.contains(&vfs_root_path) {
extern_source_roots.insert(vfs_root_path, ExternSourceId(r.0));
}
2018-09-04 11:40:45 +03:00
}
2018-08-17 19:54:08 +03:00
2020-03-31 22:29:27 +08:00
let proc_macro_client = match &config.proc_macro_srv {
2020-03-27 04:26:34 +08:00
None => ProcMacroClient::dummy(),
2020-04-20 21:26:10 +03:00
Some((path, args)) => match ProcMacroClient::extern_process(path.into(), args) {
Ok(it) => it,
Err(err) => {
log::error!(
2020-04-23 02:00:56 +03:00
"Failed to run ra_proc_macro_srv from path {}, error: {:?}",
path.display(),
2020-04-20 21:26:10 +03:00
err
);
ProcMacroClient::dummy()
2020-03-27 04:26:34 +08:00
}
2020-04-20 21:26:10 +03:00
},
2020-03-27 04:26:34 +08:00
};
2020-03-18 20:56:46 +08:00
2020-05-09 21:25:10 +03:00
// Create crate graph from all the workspaces
let mut crate_graph = CrateGraph::default();
let mut load = |path: &Path| {
// Some path from metadata will be non canonicalized, e.g. /foo/../bar/lib.rs
let path = path.canonicalize().ok()?;
let vfs_file = vfs.load(&path);
vfs_file.map(|f| FileId(f.0))
};
for ws in workspaces.iter() {
crate_graph.extend(ws.to_crate_graph(
config.cargo.target.as_deref(),
2020-05-09 21:25:10 +03:00
&extern_source_roots,
&proc_macro_client,
&mut load,
));
}
change.set_crate_graph(crate_graph);
2018-12-19 15:04:15 +03:00
2020-04-01 18:41:43 +02:00
let flycheck = config.check.as_ref().and_then(|c| create_flycheck(&workspaces, c));
2020-03-10 18:56:15 +01:00
let mut analysis_host = AnalysisHost::new(lru_capacity);
2018-12-19 15:04:15 +03:00
analysis_host.apply_change(change);
2020-06-03 11:16:08 +02:00
GlobalState {
2020-04-19 15:15:49 -04:00
config,
2020-06-03 10:52:35 +02:00
local_roots,
2018-12-19 15:04:15 +03:00
workspaces: Arc::new(workspaces),
analysis_host,
vfs: Arc::new(RwLock::new(vfs)),
2019-08-25 13:04:56 +03:00
task_receiver,
latest_requests: Default::default(),
flycheck,
diagnostics: Default::default(),
2020-04-13 00:05:33 +08:00
proc_macro_client,
2018-12-19 15:04:15 +03:00
}
}
2020-04-01 18:41:43 +02:00
pub fn update_configuration(&mut self, config: Config) {
self.analysis_host.update_lru_capacity(config.lru_capacity);
if config.check != self.config.check {
self.flycheck =
config.check.as_ref().and_then(|it| create_flycheck(&self.workspaces, it));
}
2020-03-31 16:02:55 +02:00
self.config = config;
}
2018-12-19 15:04:15 +03:00
/// Returns a vec of libraries
/// FIXME: better API here
pub fn process_changes(&mut self, roots_scanned: &mut usize) -> bool {
2018-12-19 15:40:42 +03:00
let changes = self.vfs.write().commit_changes();
if changes.is_empty() {
return false;
2018-12-19 15:40:42 +03:00
}
2018-12-19 15:04:15 +03:00
let mut change = AnalysisChange::new();
2018-12-19 15:40:42 +03:00
for c in changes {
2018-12-19 15:04:15 +03:00
match c {
VfsChange::AddRoot { root, files } => {
*roots_scanned += 1;
for (file, path, text) in files {
change.add_file(SourceRootId(root.0), FileId(file.0), path, text);
2018-12-19 15:40:42 +03:00
}
2018-12-19 15:04:15 +03:00
}
2019-02-08 14:49:43 +03:00
VfsChange::AddFile { root, file, path, text } => {
2019-06-03 10:21:08 -04:00
change.add_file(SourceRootId(root.0), FileId(file.0), path, text);
2018-12-19 15:04:15 +03:00
}
VfsChange::RemoveFile { root, file, path } => {
2019-06-03 10:21:08 -04:00
change.remove_file(SourceRootId(root.0), FileId(file.0), path)
2018-12-19 15:04:15 +03:00
}
VfsChange::ChangeFile { file, text } => {
2019-06-03 10:21:08 -04:00
change.change_file(FileId(file.0), text);
2018-12-19 15:04:15 +03:00
}
}
}
self.analysis_host.apply_change(change);
true
2018-12-19 15:04:15 +03:00
}
2020-06-03 11:16:08 +02:00
pub fn snapshot(&self) -> GlobalStateSnapshot {
GlobalStateSnapshot {
2020-03-31 16:02:55 +02:00
config: self.config.clone(),
2018-09-02 14:46:15 +03:00
workspaces: Arc::clone(&self.workspaces),
2018-09-10 12:57:40 +03:00
analysis: self.analysis_host.analysis(),
2018-12-19 15:04:15 +03:00
vfs: Arc::clone(&self.vfs),
latest_requests: Arc::clone(&self.latest_requests),
check_fixes: Arc::clone(&self.diagnostics.check_fixes),
2018-08-17 19:54:08 +03:00
}
}
2019-01-25 19:11:58 +03:00
2019-01-26 20:33:33 +03:00
pub fn maybe_collect_garbage(&mut self) {
self.analysis_host.maybe_collect_garbage()
}
pub fn collect_garbage(&mut self) {
2019-01-25 19:11:58 +03:00
self.analysis_host.collect_garbage()
}
2019-05-29 15:42:14 +03:00
2020-06-20 23:08:01 +02:00
pub(crate) fn complete_request(&mut self, request: RequestMetrics) {
self.latest_requests.write().record(request)
2019-05-29 15:42:14 +03:00
}
2018-08-17 19:54:08 +03:00
}
2020-06-03 11:16:08 +02:00
impl GlobalStateSnapshot {
2018-08-29 18:03:14 +03:00
pub fn analysis(&self) -> &Analysis {
2018-08-17 19:54:08 +03:00
&self.analysis
}
2020-06-13 11:00:06 +02:00
pub fn url_to_file_id(&self, url: &Url) -> Result<FileId> {
let path = url.to_file_path().map_err(|()| format!("invalid uri: {}", url))?;
let file = self.vfs.read().path2file(&path).ok_or_else(|| {
2019-04-07 18:26:02 +08:00
// Show warning as this file is outside current workspace
// FIXME: just handle such files, and remove `LspError::UNKNOWN_FILE`.
LspError {
code: LspError::UNKNOWN_FILE,
2019-04-07 18:26:02 +08:00
message: "Rust file outside current workspace is not supported yet.".to_string(),
}
})?;
2019-06-03 10:21:08 -04:00
Ok(FileId(file.0))
2018-08-17 19:54:08 +03:00
}
2020-06-13 11:00:06 +02:00
pub fn file_id_to_url(&self, id: FileId) -> Url {
file_id_to_url(&self.vfs.read(), id)
2018-08-17 19:54:08 +03:00
}
2018-12-21 12:18:14 +03:00
2019-08-20 18:53:59 +03:00
pub fn file_line_endings(&self, id: FileId) -> LineEndings {
self.vfs.read().file_line_endings(VfsFile(id.0))
}
pub fn anchored_path(&self, file_id: FileId, path: &str) -> Url {
let mut base = self.vfs.read().file2path(VfsFile(file_id.0));
base.pop();
let path = base.join(path);
2020-06-13 11:00:06 +02:00
url_from_abs_path(&path)
2018-12-21 12:18:14 +03:00
}
2019-01-23 00:15:03 +03:00
pub(crate) fn cargo_target_for_crate_root(
&self,
crate_id: CrateId,
) -> Option<(&CargoWorkspace, Target)> {
let file_id = self.analysis().crate_root(crate_id).ok()?;
let path = self.vfs.read().file2path(VfsFile(file_id.0));
self.workspaces.iter().find_map(|ws| match ws {
ProjectWorkspace::Cargo { cargo, .. } => {
cargo.target_by_root(&path).map(|it| (cargo, it))
}
ProjectWorkspace::Json { .. } => None,
})
}
2019-01-23 00:15:03 +03:00
pub fn status(&self) -> String {
2020-03-28 11:08:19 +01:00
let mut buf = String::new();
2019-01-23 00:15:03 +03:00
if self.workspaces.is_empty() {
2020-03-28 11:08:19 +01:00
buf.push_str("no workspaces\n")
2019-01-23 00:15:03 +03:00
} else {
2020-03-28 11:08:19 +01:00
buf.push_str("workspaces:\n");
2019-01-23 00:15:03 +03:00
for w in self.workspaces.iter() {
2020-03-28 11:08:19 +01:00
format_to!(buf, "{} packages loaded\n", w.n_packages());
2019-01-23 00:15:03 +03:00
}
}
2020-03-28 11:08:19 +01:00
buf.push_str("\nanalysis:\n");
buf.push_str(
2019-07-25 20:22:41 +03:00
&self
.analysis
.status()
.unwrap_or_else(|_| "Analysis retrieval was cancelled".to_owned()),
);
2020-03-28 11:08:19 +01:00
buf
2019-01-23 00:15:03 +03:00
}
pub fn workspace_root_for(&self, file_id: FileId) -> Option<&Path> {
2019-06-03 10:21:08 -04:00
let path = self.vfs.read().file2path(VfsFile(file_id.0));
self.workspaces.iter().find_map(|ws| ws.workspace_root_for(&path))
}
2018-08-17 19:54:08 +03:00
}
2020-06-13 11:00:06 +02:00
pub(crate) fn file_id_to_url(vfs: &Vfs, id: FileId) -> Url {
let path = vfs.file2path(VfsFile(id.0));
url_from_abs_path(&path)
}