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) enum ProjectWorkspaceProgress {
26 pub(crate) fn update_configuration(&mut self, config: Config) {
27 let _p = profile::span("GlobalState::update_configuration");
28 let old_config = mem::replace(&mut self.config, Arc::new(config));
29 if self.config.lru_capacity() != old_config.lru_capacity() {
30 self.analysis_host.update_lru_capacity(self.config.lru_capacity());
32 if self.config.linked_projects() != old_config.linked_projects() {
33 self.fetch_workspaces()
34 } else if self.config.flycheck() != old_config.flycheck() {
35 self.reload_flycheck();
38 pub(crate) fn maybe_refresh(&mut self, changes: &[(AbsPathBuf, ChangeKind)]) {
39 if !changes.iter().any(|(path, kind)| is_interesting(path, *kind)) {
43 Status::Loading | Status::NeedsReload => return,
44 Status::Ready | Status::Invalid => (),
46 if self.config.cargo_autoreload() {
47 self.fetch_workspaces();
49 self.transition(Status::NeedsReload);
52 fn is_interesting(path: &AbsPath, change_kind: ChangeKind) -> bool {
53 const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
54 const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
56 if path.ends_with("Cargo.toml") || path.ends_with("Cargo.lock") {
59 if change_kind == ChangeKind::Modify {
62 if path.extension().unwrap_or_default() != "rs" {
65 if IMPLICIT_TARGET_FILES.iter().any(|it| path.ends_with(it)) {
68 let parent = match path.parent() {
72 if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.ends_with(it)) {
75 if path.ends_with("main.rs") {
76 let grand_parent = match parent.parent() {
80 if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.ends_with(it)) {
87 pub(crate) fn transition(&mut self, new_status: Status) {
88 self.status = new_status;
89 if self.config.status_notification() {
90 let lsp_status = match new_status {
91 Status::Loading => lsp_ext::Status::Loading,
92 Status::Ready => lsp_ext::Status::Ready,
93 Status::Invalid => lsp_ext::Status::Invalid,
94 Status::NeedsReload => lsp_ext::Status::NeedsReload,
96 self.send_notification::<lsp_ext::StatusNotification>(StatusParams {
101 pub(crate) fn fetch_workspaces(&mut self) {
102 log::info!("will fetch workspaces");
104 self.task_pool.handle.spawn_with_sender({
105 let linked_projects = self.config.linked_projects();
106 let cargo_config = self.config.cargo();
110 let sender = sender.clone();
113 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
118 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
120 let workspaces = linked_projects
122 .map(|project| match project {
123 LinkedProject::ProjectManifest(manifest) => {
124 project_model::ProjectWorkspace::load(
130 LinkedProject::InlineJsonProject(it) => {
131 project_model::ProjectWorkspace::load_inline(it.clone())
134 .collect::<Vec<_>>();
136 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::End)).unwrap();
137 log::info!("did fetch workspaces {:?}", workspaces);
138 sender.send(Task::Workspaces(workspaces)).unwrap()
142 pub(crate) fn switch_workspaces(&mut self, workspaces: Vec<anyhow::Result<ProjectWorkspace>>) {
143 let _p = profile::span("GlobalState::switch_workspaces");
144 log::info!("will switch workspaces: {:?}", workspaces);
146 let mut has_errors = false;
147 let workspaces = workspaces
152 log::error!("failed to load workspace: {:#}", err);
153 if self.workspaces.is_empty() {
155 lsp_types::MessageType::Error,
156 format!("rust-analyzer failed to load workspace: {:#}", err),
162 .collect::<Vec<_>>();
164 if &*self.workspaces == &workspaces {
168 if !self.workspaces.is_empty() && has_errors {
172 if let FilesWatcher::Client = self.config.files().watcher {
173 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
176 .flat_map(ProjectWorkspace::to_roots)
177 .filter(|it| it.is_member)
179 root.include.into_iter().map(|it| format!("{}/**/*.rs", it.display()))
181 .map(|glob_pattern| lsp_types::FileSystemWatcher { glob_pattern, kind: None })
184 let registration = lsp_types::Registration {
185 id: "workspace/didChangeWatchedFiles".to_string(),
186 method: "workspace/didChangeWatchedFiles".to_string(),
187 register_options: Some(serde_json::to_value(registration_options).unwrap()),
189 self.send_request::<lsp_types::request::RegisterCapability>(
190 lsp_types::RegistrationParams { registrations: vec![registration] },
195 let mut change = Change::new();
197 let project_folders = ProjectFolders::new(&workspaces);
199 self.proc_macro_client = match self.config.proc_macro_srv() {
201 Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) {
205 "Failed to run proc_macro_srv from path {}, error: {:?}",
214 let watch = match self.config.files().watcher {
215 FilesWatcher::Client => vec![],
216 FilesWatcher::Notify => project_folders.watch,
218 self.loader.handle.set_config(vfs::loader::Config { load: project_folders.load, watch });
220 // Create crate graph from all the workspaces
222 let mut crate_graph = CrateGraph::default();
223 let vfs = &mut self.vfs.write().0;
224 let loader = &mut self.loader;
225 let mem_docs = &self.mem_docs;
226 let mut load = |path: &AbsPath| {
227 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
228 if !mem_docs.contains_key(&vfs_path) {
229 let contents = loader.handle.load_sync(path);
230 vfs.set_file_contents(vfs_path.clone(), contents);
232 let res = vfs.file_id(&vfs_path);
234 log::warn!("failed to load {}", path.display())
238 for ws in workspaces.iter() {
239 crate_graph.extend(ws.to_crate_graph(
240 self.config.cargo().target.as_deref(),
241 self.proc_macro_client.as_ref(),
248 change.set_crate_graph(crate_graph);
250 self.source_root_config = project_folders.source_root_config;
251 self.workspaces = Arc::new(workspaces);
253 self.analysis_host.apply_change(change);
254 self.process_changes();
255 self.reload_flycheck();
256 log::info!("did switch workspaces");
259 fn reload_flycheck(&mut self) {
260 let config = match self.config.flycheck() {
263 self.flycheck = Vec::new();
268 let sender = self.flycheck_sender.clone();
273 .filter_map(|(id, w)| match w {
274 ProjectWorkspace::Cargo { cargo, sysroot: _, rustc: _ } => {
275 Some((id, cargo.workspace_root()))
277 ProjectWorkspace::Json { project, .. } => {
278 // Enable flychecks for json projects if a custom flycheck command was supplied
279 // in the workspace configuration.
281 FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
287 let sender = sender.clone();
288 FlycheckHandle::spawn(
290 Box::new(move |msg| sender.send(msg).unwrap()),
292 root.to_path_buf().into(),
300 pub(crate) struct ProjectFolders {
301 pub(crate) load: Vec<vfs::loader::Entry>,
302 pub(crate) watch: Vec<usize>,
303 pub(crate) source_root_config: SourceRootConfig,
306 impl ProjectFolders {
307 pub(crate) fn new(workspaces: &[ProjectWorkspace]) -> ProjectFolders {
308 let mut res = ProjectFolders::default();
309 let mut fsc = FileSetConfig::builder();
310 let mut local_filesets = vec![];
312 for root in workspaces.iter().flat_map(|it| it.to_roots()) {
313 let file_set_roots: Vec<VfsPath> =
314 root.include.iter().cloned().map(VfsPath::from).collect();
317 let mut dirs = vfs::loader::Directories::default();
318 dirs.extensions.push("rs".into());
319 dirs.include.extend(root.include);
320 dirs.exclude.extend(root.exclude);
321 vfs::loader::Entry::Directories(dirs)
325 res.watch.push(res.load.len());
327 res.load.push(entry);
330 local_filesets.push(fsc.len());
332 fsc.add_file_set(file_set_roots)
335 let fsc = fsc.build();
336 res.source_root_config = SourceRootConfig { fsc, local_filesets };
342 #[derive(Default, Debug)]
343 pub(crate) struct SourceRootConfig {
344 pub(crate) fsc: FileSetConfig,
345 pub(crate) local_filesets: Vec<usize>,
348 impl SourceRootConfig {
349 pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
350 let _p = profile::span("SourceRootConfig::partition");
355 .map(|(idx, file_set)| {
356 let is_local = self.local_filesets.contains(&idx);
358 SourceRoot::new_local(file_set)
360 SourceRoot::new_library(file_set)