1 //! Project loading & configuration updates
2 use std::{mem, sync::Arc};
4 use flycheck::{FlycheckConfig, FlycheckHandle};
6 use ide_db::base_db::{CrateGraph, SourceRoot, VfsPath};
7 use project_model::{ProcMacroClient, ProjectWorkspace};
8 use vfs::{file_set::FileSetConfig, AbsPath, AbsPathBuf, ChangeKind};
11 config::{Config, FilesWatcher, LinkedProject},
12 global_state::{GlobalState, Status},
16 use lsp_ext::StatusParams;
19 pub(crate) fn update_configuration(&mut self, config: Config) {
20 let _p = profile::span("GlobalState::update_configuration");
21 let old_config = mem::replace(&mut self.config, config);
22 if self.config.lru_capacity != old_config.lru_capacity {
23 self.analysis_host.update_lru_capacity(old_config.lru_capacity);
25 if self.config.linked_projects != old_config.linked_projects {
26 self.fetch_workspaces()
27 } else if self.config.flycheck != old_config.flycheck {
28 self.reload_flycheck();
31 pub(crate) fn maybe_refresh(&mut self, changes: &[(AbsPathBuf, ChangeKind)]) {
32 if !changes.iter().any(|(path, kind)| is_interesting(path, *kind)) {
36 Status::Loading | Status::NeedsReload => return,
37 Status::Ready | Status::Invalid => (),
39 if self.config.cargo_autoreload {
40 self.fetch_workspaces();
42 self.transition(Status::NeedsReload);
45 fn is_interesting(path: &AbsPath, change_kind: ChangeKind) -> bool {
46 const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
47 const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
49 if path.ends_with("Cargo.toml") || path.ends_with("Cargo.lock") {
52 if change_kind == ChangeKind::Modify {
55 if path.extension().unwrap_or_default() != "rs" {
58 if IMPLICIT_TARGET_FILES.iter().any(|it| path.ends_with(it)) {
61 let parent = match path.parent() {
65 if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.ends_with(it)) {
68 if path.ends_with("main.rs") {
69 let grand_parent = match parent.parent() {
73 if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.ends_with(it)) {
80 pub(crate) fn transition(&mut self, new_status: Status) {
81 self.status = new_status;
82 if self.config.client_caps.status_notification {
83 let lsp_status = match new_status {
84 Status::Loading => lsp_ext::Status::Loading,
85 Status::Ready => lsp_ext::Status::Ready,
86 Status::Invalid => lsp_ext::Status::Invalid,
87 Status::NeedsReload => lsp_ext::Status::NeedsReload,
89 self.send_notification::<lsp_ext::StatusNotification>(StatusParams {
94 pub(crate) fn fetch_workspaces(&mut self) {
95 log::info!("will fetch workspaces");
96 self.task_pool.handle.spawn({
97 let linked_projects = self.config.linked_projects.clone();
98 let cargo_config = self.config.cargo.clone();
99 let with_sysroot = self.config.with_sysroot.clone();
101 let workspaces = linked_projects
103 .map(|project| match project {
104 LinkedProject::ProjectManifest(manifest) => {
105 project_model::ProjectWorkspace::load(
111 LinkedProject::InlineJsonProject(it) => {
112 project_model::ProjectWorkspace::load_inline(it.clone())
115 .collect::<Vec<_>>();
116 log::info!("did fetch workspaces {:?}", workspaces);
117 Task::Workspaces(workspaces)
121 pub(crate) fn switch_workspaces(&mut self, workspaces: Vec<anyhow::Result<ProjectWorkspace>>) {
122 let _p = profile::span("GlobalState::switch_workspaces");
123 log::info!("will switch workspaces: {:?}", workspaces);
125 let mut has_errors = false;
126 let workspaces = workspaces
131 log::error!("failed to load workspace: {:#}", err);
132 if self.workspaces.is_empty() {
134 lsp_types::MessageType::Error,
135 format!("rust-analyzer failed to load workspace: {:#}", err),
141 .collect::<Vec<_>>();
143 if &*self.workspaces == &workspaces {
147 if !self.workspaces.is_empty() && has_errors {
151 if let FilesWatcher::Client = self.config.files.watcher {
152 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
155 .flat_map(ProjectWorkspace::to_roots)
156 .filter(|it| it.is_member)
158 root.include.into_iter().map(|it| format!("{}/**/*.rs", it.display()))
160 .map(|glob_pattern| lsp_types::FileSystemWatcher { glob_pattern, kind: None })
163 let registration = lsp_types::Registration {
164 id: "workspace/didChangeWatchedFiles".to_string(),
165 method: "workspace/didChangeWatchedFiles".to_string(),
166 register_options: Some(serde_json::to_value(registration_options).unwrap()),
168 self.send_request::<lsp_types::request::RegisterCapability>(
169 lsp_types::RegistrationParams { registrations: vec![registration] },
174 let mut change = Change::new();
176 let project_folders = ProjectFolders::new(&workspaces);
178 self.proc_macro_client = match &self.config.proc_macro_srv {
179 None => ProcMacroClient::dummy(),
180 Some((path, args)) => match ProcMacroClient::extern_process(path.into(), args) {
184 "Failed to run proc_macro_srv from path {}, error: {:?}",
188 ProcMacroClient::dummy()
193 let watch = match self.config.files.watcher {
194 FilesWatcher::Client => vec![],
195 FilesWatcher::Notify => project_folders.watch,
197 self.loader.handle.set_config(vfs::loader::Config { load: project_folders.load, watch });
199 // Create crate graph from all the workspaces
201 let mut crate_graph = CrateGraph::default();
202 let vfs = &mut self.vfs.write().0;
203 let loader = &mut self.loader;
204 let mem_docs = &self.mem_docs;
205 let mut load = |path: &AbsPath| {
206 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
207 if !mem_docs.contains_key(&vfs_path) {
208 let contents = loader.handle.load_sync(path);
209 vfs.set_file_contents(vfs_path.clone(), contents);
211 vfs.file_id(&vfs_path)
213 for ws in workspaces.iter() {
214 crate_graph.extend(ws.to_crate_graph(
215 self.config.cargo.target.as_deref(),
216 &self.proc_macro_client,
223 change.set_crate_graph(crate_graph);
225 self.source_root_config = project_folders.source_root_config;
226 self.workspaces = Arc::new(workspaces);
228 self.analysis_host.apply_change(change);
229 self.process_changes();
230 self.reload_flycheck();
231 log::info!("did switch workspaces");
234 fn reload_flycheck(&mut self) {
235 let config = match self.config.flycheck.clone() {
238 self.flycheck = Vec::new();
243 let sender = self.flycheck_sender.clone();
248 .filter_map(|(id, w)| match w {
249 ProjectWorkspace::Cargo { cargo, sysroot: _, rustc: _ } => {
250 Some((id, cargo.workspace_root()))
252 ProjectWorkspace::Json { project, .. } => {
253 // Enable flychecks for json projects if a custom flycheck command was supplied
254 // in the workspace configuration.
256 FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
262 let sender = sender.clone();
263 FlycheckHandle::spawn(
265 Box::new(move |msg| sender.send(msg).unwrap()),
267 root.to_path_buf().into(),
275 pub(crate) struct ProjectFolders {
276 pub(crate) load: Vec<vfs::loader::Entry>,
277 pub(crate) watch: Vec<usize>,
278 pub(crate) source_root_config: SourceRootConfig,
281 impl ProjectFolders {
282 pub(crate) fn new(workspaces: &[ProjectWorkspace]) -> ProjectFolders {
283 let mut res = ProjectFolders::default();
284 let mut fsc = FileSetConfig::builder();
285 let mut local_filesets = vec![];
287 for root in workspaces.iter().flat_map(|it| it.to_roots()) {
288 let file_set_roots: Vec<VfsPath> =
289 root.include.iter().cloned().map(VfsPath::from).collect();
292 let mut dirs = vfs::loader::Directories::default();
293 dirs.extensions.push("rs".into());
294 dirs.include.extend(root.include);
295 dirs.exclude.extend(root.exclude);
296 vfs::loader::Entry::Directories(dirs)
300 res.watch.push(res.load.len());
302 res.load.push(entry);
305 local_filesets.push(fsc.len());
307 fsc.add_file_set(file_set_roots)
310 let fsc = fsc.build();
311 res.source_root_config = SourceRootConfig { fsc, local_filesets };
317 #[derive(Default, Debug)]
318 pub(crate) struct SourceRootConfig {
319 pub(crate) fsc: FileSetConfig,
320 pub(crate) local_filesets: Vec<usize>,
323 impl SourceRootConfig {
324 pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
325 let _p = profile::span("SourceRootConfig::partition");
330 .map(|(idx, file_set)| {
331 let is_local = self.local_filesets.contains(&idx);
333 SourceRoot::new_local(file_set)
335 SourceRoot::new_library(file_set)