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 {
22 End(Vec<anyhow::Result<ProjectWorkspace>>),
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_request()
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_request();
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 {
102 pub(crate) fn fetch_workspaces_request(&mut self) {
103 self.fetch_workspaces_queue.request_op()
105 pub(crate) fn fetch_workspaces_if_needed(&mut self) {
106 log::info!("will fetch workspaces");
107 if !self.fetch_workspaces_queue.should_start_op() {
111 self.task_pool.handle.spawn_with_sender({
112 let linked_projects = self.config.linked_projects();
113 let cargo_config = self.config.cargo();
117 let sender = sender.clone();
120 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
125 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
127 let workspaces = linked_projects
129 .map(|project| match project {
130 LinkedProject::ProjectManifest(manifest) => {
131 project_model::ProjectWorkspace::load(
137 LinkedProject::InlineJsonProject(it) => {
138 project_model::ProjectWorkspace::load_inline(it.clone())
141 .collect::<Vec<_>>();
143 log::info!("did fetch workspaces {:?}", workspaces);
145 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(workspaces)))
150 pub(crate) fn fetch_workspaces_completed(&mut self) {
151 self.fetch_workspaces_queue.op_completed()
154 pub(crate) fn switch_workspaces(&mut self, workspaces: Vec<anyhow::Result<ProjectWorkspace>>) {
155 let _p = profile::span("GlobalState::switch_workspaces");
156 log::info!("will switch workspaces: {:?}", workspaces);
158 let mut has_errors = false;
159 let workspaces = workspaces
164 log::error!("failed to load workspace: {:#}", err);
165 if self.workspaces.is_empty() {
167 lsp_types::MessageType::Error,
168 format!("rust-analyzer failed to load workspace: {:#}", err),
174 .collect::<Vec<_>>();
176 if &*self.workspaces == &workspaces {
180 if !self.workspaces.is_empty() && has_errors {
184 if let FilesWatcher::Client = self.config.files().watcher {
185 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
188 .flat_map(ProjectWorkspace::to_roots)
189 .filter(|it| it.is_member)
191 root.include.into_iter().map(|it| format!("{}/**/*.rs", it.display()))
193 .map(|glob_pattern| lsp_types::FileSystemWatcher { glob_pattern, kind: None })
196 let registration = lsp_types::Registration {
197 id: "workspace/didChangeWatchedFiles".to_string(),
198 method: "workspace/didChangeWatchedFiles".to_string(),
199 register_options: Some(serde_json::to_value(registration_options).unwrap()),
201 self.send_request::<lsp_types::request::RegisterCapability>(
202 lsp_types::RegistrationParams { registrations: vec![registration] },
207 let mut change = Change::new();
209 let project_folders = ProjectFolders::new(&workspaces);
211 self.proc_macro_client = match self.config.proc_macro_srv() {
213 Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) {
217 "Failed to run proc_macro_srv from path {}, error: {:?}",
226 let watch = match self.config.files().watcher {
227 FilesWatcher::Client => vec![],
228 FilesWatcher::Notify => project_folders.watch,
230 self.loader.handle.set_config(vfs::loader::Config { load: project_folders.load, watch });
232 // Create crate graph from all the workspaces
234 let mut crate_graph = CrateGraph::default();
235 let vfs = &mut self.vfs.write().0;
236 let loader = &mut self.loader;
237 let mem_docs = &self.mem_docs;
238 let mut load = |path: &AbsPath| {
239 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
240 if !mem_docs.contains_key(&vfs_path) {
241 let contents = loader.handle.load_sync(path);
242 vfs.set_file_contents(vfs_path.clone(), contents);
244 let res = vfs.file_id(&vfs_path);
246 log::warn!("failed to load {}", path.display())
250 for ws in workspaces.iter() {
251 crate_graph.extend(ws.to_crate_graph(
252 self.config.cargo().target.as_deref(),
253 self.proc_macro_client.as_ref(),
260 change.set_crate_graph(crate_graph);
262 self.source_root_config = project_folders.source_root_config;
263 self.workspaces = Arc::new(workspaces);
265 self.analysis_host.apply_change(change);
266 self.process_changes();
267 self.reload_flycheck();
268 log::info!("did switch workspaces");
271 fn reload_flycheck(&mut self) {
272 let config = match self.config.flycheck() {
275 self.flycheck = Vec::new();
280 let sender = self.flycheck_sender.clone();
285 .filter_map(|(id, w)| match w {
286 ProjectWorkspace::Cargo { cargo, sysroot: _, rustc: _ } => {
287 Some((id, cargo.workspace_root()))
289 ProjectWorkspace::Json { project, .. } => {
290 // Enable flychecks for json projects if a custom flycheck command was supplied
291 // in the workspace configuration.
293 FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
299 let sender = sender.clone();
300 FlycheckHandle::spawn(
302 Box::new(move |msg| sender.send(msg).unwrap()),
304 root.to_path_buf().into(),
312 pub(crate) struct ProjectFolders {
313 pub(crate) load: Vec<vfs::loader::Entry>,
314 pub(crate) watch: Vec<usize>,
315 pub(crate) source_root_config: SourceRootConfig,
318 impl ProjectFolders {
319 pub(crate) fn new(workspaces: &[ProjectWorkspace]) -> ProjectFolders {
320 let mut res = ProjectFolders::default();
321 let mut fsc = FileSetConfig::builder();
322 let mut local_filesets = vec![];
324 for root in workspaces.iter().flat_map(|it| it.to_roots()) {
325 let file_set_roots: Vec<VfsPath> =
326 root.include.iter().cloned().map(VfsPath::from).collect();
329 let mut dirs = vfs::loader::Directories::default();
330 dirs.extensions.push("rs".into());
331 dirs.include.extend(root.include);
332 dirs.exclude.extend(root.exclude);
333 vfs::loader::Entry::Directories(dirs)
337 res.watch.push(res.load.len());
339 res.load.push(entry);
342 local_filesets.push(fsc.len());
344 fsc.add_file_set(file_set_roots)
347 let fsc = fsc.build();
348 res.source_root_config = SourceRootConfig { fsc, local_filesets };
354 #[derive(Default, Debug)]
355 pub(crate) struct SourceRootConfig {
356 pub(crate) fsc: FileSetConfig,
357 pub(crate) local_filesets: Vec<usize>,
360 impl SourceRootConfig {
361 pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
362 let _p = profile::span("SourceRootConfig::partition");
367 .map(|(idx, file_set)| {
368 let is_local = self.local_filesets.contains(&idx);
370 SourceRoot::new_local(file_set)
372 SourceRoot::new_library(file_set)