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 if self.config.did_change_watched_files_dynamic_registration() {
186 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
189 .flat_map(ProjectWorkspace::to_roots)
190 .filter(|it| it.is_member)
192 root.include.into_iter().map(|it| format!("{}/**/*.rs", it.display()))
194 .map(|glob_pattern| lsp_types::FileSystemWatcher {
200 let registration = lsp_types::Registration {
201 id: "workspace/didChangeWatchedFiles".to_string(),
202 method: "workspace/didChangeWatchedFiles".to_string(),
203 register_options: Some(serde_json::to_value(registration_options).unwrap()),
205 self.send_request::<lsp_types::request::RegisterCapability>(
206 lsp_types::RegistrationParams { registrations: vec![registration] },
212 let mut change = Change::new();
214 let project_folders = ProjectFolders::new(&workspaces);
216 self.proc_macro_client = match self.config.proc_macro_srv() {
218 Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) {
222 "Failed to run proc_macro_srv from path {}, error: {:?}",
231 let watch = match self.config.files().watcher {
232 FilesWatcher::Client => vec![],
233 FilesWatcher::Notify => project_folders.watch,
235 self.loader.handle.set_config(vfs::loader::Config { load: project_folders.load, watch });
237 // Create crate graph from all the workspaces
239 let mut crate_graph = CrateGraph::default();
240 let vfs = &mut self.vfs.write().0;
241 let loader = &mut self.loader;
242 let mem_docs = &self.mem_docs;
243 let mut load = |path: &AbsPath| {
244 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
245 if !mem_docs.contains_key(&vfs_path) {
246 let contents = loader.handle.load_sync(path);
247 vfs.set_file_contents(vfs_path.clone(), contents);
249 let res = vfs.file_id(&vfs_path);
251 log::warn!("failed to load {}", path.display())
255 for ws in workspaces.iter() {
256 crate_graph.extend(ws.to_crate_graph(
257 self.config.cargo().target.as_deref(),
258 self.proc_macro_client.as_ref(),
265 change.set_crate_graph(crate_graph);
267 self.source_root_config = project_folders.source_root_config;
268 self.workspaces = Arc::new(workspaces);
270 self.analysis_host.apply_change(change);
271 self.process_changes();
272 self.reload_flycheck();
273 log::info!("did switch workspaces");
276 fn reload_flycheck(&mut self) {
277 let _p = profile::span("GlobalState::reload_flycheck");
278 let config = match self.config.flycheck() {
281 self.flycheck = Vec::new();
286 let sender = self.flycheck_sender.clone();
291 .filter_map(|(id, w)| match w {
292 ProjectWorkspace::Cargo { cargo, sysroot: _, rustc: _ } => {
293 Some((id, cargo.workspace_root()))
295 ProjectWorkspace::Json { project, .. } => {
296 // Enable flychecks for json projects if a custom flycheck command was supplied
297 // in the workspace configuration.
299 FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
305 let sender = sender.clone();
306 FlycheckHandle::spawn(
308 Box::new(move |msg| sender.send(msg).unwrap()),
310 root.to_path_buf().into(),
318 pub(crate) struct ProjectFolders {
319 pub(crate) load: Vec<vfs::loader::Entry>,
320 pub(crate) watch: Vec<usize>,
321 pub(crate) source_root_config: SourceRootConfig,
324 impl ProjectFolders {
325 pub(crate) fn new(workspaces: &[ProjectWorkspace]) -> ProjectFolders {
326 let mut res = ProjectFolders::default();
327 let mut fsc = FileSetConfig::builder();
328 let mut local_filesets = vec![];
330 for root in workspaces.iter().flat_map(|it| it.to_roots()) {
331 let file_set_roots: Vec<VfsPath> =
332 root.include.iter().cloned().map(VfsPath::from).collect();
335 let mut dirs = vfs::loader::Directories::default();
336 dirs.extensions.push("rs".into());
337 dirs.include.extend(root.include);
338 dirs.exclude.extend(root.exclude);
339 vfs::loader::Entry::Directories(dirs)
343 res.watch.push(res.load.len());
345 res.load.push(entry);
348 local_filesets.push(fsc.len());
350 fsc.add_file_set(file_set_roots)
353 let fsc = fsc.build();
354 res.source_root_config = SourceRootConfig { fsc, local_filesets };
360 #[derive(Default, Debug)]
361 pub(crate) struct SourceRootConfig {
362 pub(crate) fsc: FileSetConfig,
363 pub(crate) local_filesets: Vec<usize>,
366 impl SourceRootConfig {
367 pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
368 let _p = profile::span("SourceRootConfig::partition");
373 .map(|(idx, file_set)| {
374 let is_local = self.local_filesets.contains(&idx);
376 SourceRoot::new_local(file_set)
378 SourceRoot::new_library(file_set)